Web CryptでAES-GCMの鍵を生成してJWKインポート/エクスポートして暗号化/復号する
#Web_Crypto #AES-GCM #セキュリティ
code:js
(async () => {
const iv = crypto.getRandomValues(new Uint8Array(12));
// (base: https://8gwifi.org/docs/window-crypto-aes2.jsp)
const aKey = await window.crypto.subtle.generateKey(
{ name: "AES-GCM", length: 256 },
true,
"encrypt", "decrypt"
);
const aKeyJWK = await crypto.subtle.exportKey('jwk', aKey);
const bKey = await crypto.subtle.importKey(
'jwk',
aKeyJWK,
{ name: "AES-GCM", length: 256 },
false,
'encrypt', 'decrypt'
);
const raw = new Uint8Array(1, 2, 3);
const encrypted = await crypto.subtle.encrypt(
{ name: 'AES-GCM', iv, tagLength: 128 },
aKey,
raw
);
const decrypted = await crypto.subtle.decrypt(
{ name: 'AES-GCM', iv, tagLength: 128 },
bKey,
encrypted
);
return JSON.stringify(...raw) === JSON.stringify(...new Uint8Array(decrypted));
})();
Nipp: