Skip to content

Instantly share code, notes, and snippets.

@jeffotoni
Last active July 14, 2018 12:28
Show Gist options
  • Save jeffotoni/f6f6168485f320d609491af762b2060e to your computer and use it in GitHub Desktop.
Save jeffotoni/f6f6168485f320d609491af762b2060e to your computer and use it in GitHub Desktop.
keygen/encrypt/decrypt using symmetric encryption with AES
// Resources:
// https://github.com/diafygi/webcrypto-examples
// https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey
// http://blog.engelke.com/tag/webcrypto/
// Tested in Firefox
function ArrayToBuffer(str) {
var buf = new ArrayBuffer(str.length * 2);
var bufView = new Uint16Array(buf);
for (var i = 0, strLen = str.length; i < strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}
function arrayBufferToString(buf) {
return String.fromCharCode.apply(null, new Uint16Array(buf));
}
var algoKeyGen = {
name: 'AES-GCM',
length: 256
};
var iv = window.crypto.getRandomValues(new Uint8Array(12));
var algoEncrypt = {
name: 'AES-GCM',
iv: iv,
tagLength: 128
};
var keyUsages = [
'encrypt',
'decrypt'
];
var plainText = 'This is some plaintext';
console.log('Plain Text: ' + plainText);
var secretKey;
window.crypto.subtle.generateKey(algoKeyGen, false, keyUsages).then(function (key) {
secretKey = key;
return window.crypto.subtle.encrypt(algoEncrypt, key, ArrayToBuffer(plainText));
}).then(function (cipherText) {
console.log('Cipher Text: ' + arrayBufferToString(cipherText));
return window.crypto.subtle.decrypt(algoEncrypt, secretKey, cipherText);
}).then(function (plainText) {
console.log('Plain Text: ' + arrayBufferToString(plainText));
}).catch (function (err) {
console.log('Error: ' + err.message);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment