Skip to content

Instantly share code, notes, and snippets.

@BigSully
Created November 8, 2022 15:02
Show Gist options
  • Save BigSully/95b88cff983e4fa834a4f02b1e5264a4 to your computer and use it in GitHub Desktop.
Save BigSully/95b88cff983e4fa834a4f02b1e5264a4 to your computer and use it in GitHub Desktop.
AES CBC sample(execute it on chrome console to see the result)
(async () => {
/*
Get the encoded message, encrypt it and display a representation
of the ciphertext in the "Ciphertext" element.
*/
async function encrypt(key, plainText, iv) {
let encoded = new TextEncoder().encode(plainText);
const ciphertext = await window.crypto.subtle.encrypt(
{
name: "AES-CBC",
iv
},
key,
encoded
);
return ciphertext;
}
/*
Fetch the ciphertext and decrypt it.
Write the decrypted message into the "Decrypted" box.
*/
async function decrypt(key, ciphertext, iv) {
const decrypted = await window.crypto.subtle.decrypt(
{
name: "AES-CBC",
iv
},
key,
ciphertext
);
return new TextDecoder().decode(decrypted);
}
// Uint8Array[122, 239, 98, 195, 223, 136, 255, 37, 210, 243, 97, 246, 54, 100, 114, 11] -> '122,239,98,195,223,136,255,37,210,243,97,246,54,100,114,11'
const uint8ArrayToStr = iv => iv.toString();
// '122,239,98,195,223,136,255,37,210,243,97,246,54,100,114,11' -> Uint8Array[122, 239, 98, 195, 223, 136, 255, 37, 210, 243, 97, 246, 54, 100, 114, 11]
const strToUint8Array = str => Uint8Array.from(str.split(',').map(e => parseInt(e)));
/*
Store the calculated ciphertext and IV here, so we can decrypt the message later.
*/
let iv = window.crypto.getRandomValues(new Uint8Array(16)); // The iv must never be reused with a given key.
let key = await window.crypto.subtle.generateKey(
{
name: "AES-CBC",
length: 256
},
true,
["encrypt", "decrypt"]
);
let keyArrayBuffer = await crypto.subtle.exportKey('raw', key);
let keyStr = new Uint8Array(keyArrayBuffer).toString();
console.log(`key to be kept secret: ${keyStr}`);
let plaintext = 'Hello world!';
let ciphertext = await encrypt(key, plaintext, iv);
let ciphertextStr = new Uint8Array(ciphertext).toString();
let ivStr=uint8ArrayToStr(iv);
console.log(`For public transfer, encoded data: ${ciphertextStr},\niv: ${ivStr}`);
// ------ decrypt with the information above
// restore ciphertext bytes from ciphertext string
let ciphertext2 = strToUint8Array(ciphertextStr);
// restore key bytes from key string
let keyArrayBuffer2 = strToUint8Array(keyStr);
let key2 = await crypto.subtle.importKey(
"raw",
keyArrayBuffer2.buffer,
"AES-CBC",
false,
["encrypt", "decrypt"]
);
// restore iv bytes from iv string
let iv2=strToUint8Array(ivStr);
let decText = await decrypt(key2, ciphertext2, iv2);
console.log(decText);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment