Skip to content

Instantly share code, notes, and snippets.

@andreburgaud
Created November 16, 2015 04:29
Show Gist options
  • Save andreburgaud/6f73fd2d690b629346b8 to your computer and use it in GitHub Desktop.
Save andreburgaud/6f73fd2d690b629346b8 to your computer and use it in GitHub Desktop.
Basic example of Web Crypto (keygen/encrypt/decrypt) using symmetric encryption with AES Gallois Counter Mode algorithm.
// 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 Developer Edition
function strToArrayBuffer(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, strToArrayBuffer(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);
});
@MasterJames
Copy link

What's the purpose of bufView?

@andreburgaud
Copy link
Author

I know it is an old question that I missed and that deserves an answer. In this example, bufView is a mask that defines that buffer buf represents a buffer of 16-bit unsigned integers. bufView wraps buf and allows to manipulate the bytes with the proper alignment.

For a more thorough explanation, check out https://developers.google.com/web/updates/2012/06/How-to-convert-ArrayBuffer-to-and-from-String.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment