Skip to content

Instantly share code, notes, and snippets.

@rodrigok
Created March 27, 2020 01:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rodrigok/2cc240cb64c025f12e98593500cc2f7f to your computer and use it in GitHub Desktop.
Save rodrigok/2cc240cb64c025f12e98593500cc2f7f to your computer and use it in GitHub Desktop.
Simple code to encrypt/decrypt with shared key
function ab2str(buf) {
return String.fromCharCode.apply(null, new Uint16Array(buf));
}
function str2ab(str) {
var buf = new ArrayBuffer(str.length * 2); // 2 bytes for each char
var bufView = new Uint16Array(buf);
for (var i = 0, strLen = str.length; i < strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}
async function generateKey() {
const key = await window.crypto.subtle.generateKey({
name: 'AES-GCM',
length: 256
}, true, ['encrypt', 'decrypt']);
const a = await crypto.subtle.exportKey('jwk', key);
console.log(btoa(JSON.stringify(a)));
return a;
}
/* generateKey(); */
async function getKeyFromString(keyStr) {
const key = JSON.parse(atob(keyStr))
return await crypto.subtle.importKey('jwk', key, {
name: 'AES-GCM',
length: 256
}, true, ['encrypt', 'decrypt']);
}
async function encrypt(text, key) {
const vector = crypto.getRandomValues(new Uint8Array(16));
const data = new TextEncoder('UTF-8').encode(text);
const enc = await crypto.subtle.encrypt({
name: 'AES-GCM',
iv: vector
}, key, data);
const cipherText = new Uint8Array(enc);
return encodeURIComponent(btoa(ab2str(vector) + ab2str(cipherText)));
}
async function decrypt(data, key) {
const binaryData = atob(decodeURIComponent(data));
const vector = new Uint8Array(new Uint16Array(str2ab(binaryData.slice(0, 16))));
const buffer = new Uint8Array(new Uint16Array(str2ab(binaryData.slice(16))));
const decoded = await crypto.subtle.decrypt({
name: 'AES-GCM',
iv: vector
}, key, buffer);
return new TextDecoder("UTF-8").decode(decoded);
}
const keyStr = 'eyJhbGciOiJBMjU2R0NNIiwiZXh0Ijp0cnVlLCJrIjoiQ3RDTjVXOGY4elcyN1BwTWRtaGJJVkl0ajVJWERtU3hwYzRNeWlKSGpISSIsImtleV9vcHMiOlsiZW5jcnlwdCIsImRlY3J5cHQiXSwia3R5Ijoib2N0In0=';
getKeyFromString(keyStr).then((key) => {
encrypt('rodrigo', key)
.then(async (data) => console.log(await decrypt(data, key)));
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment