Skip to content

Instantly share code, notes, and snippets.

@nov
Created April 8, 2014 16:33
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 nov/10152621 to your computer and use it in GitHub Desktop.
Save nov/10152621 to your computer and use it in GitHub Desktop.
if (!crypto.subtle) {
crypto.subtle = crypto.webkitSubtle
}
// Encrypt some data using AES-CBC and alert() the result:
// ----------------------------------------
var keyBytes1 = asciiToArrayBufferView("raw key bytes 1.");
crypto.subtle.importKey('raw', keyBytes1, {name: 'aes-cbc'}, false, ['encrypt', 'decrypt']).then(function(key) {
// Initialization vector of all zeros.
var iv = asciiToArrayBufferView("16 bytes of iv..");
var dataToEncrypt = asciiToArrayBufferView("hello world.");
return crypto.subtle.encrypt({name: 'aes-cbc', iv: iv}, key, dataToEncrypt);
}).then(function(encryptedData) {
alert('result of encryption: ' + arrayBufferToHexString(encryptedData));
}).then(undefined, function() { alert('failed :(') });
// Sign some data with SHA1 HMAC and alert() the result:
// ----------------------------------------
var keyBytes2 = asciiToArrayBufferView("raw key bytes 2.");
crypto.subtle.importKey('raw', keyBytes2, {name: 'hmac', hash: {name: 'sha-1'}}, false, ['sign']).then(function(key) {
var dataToSign = asciiToArrayBufferView("it's friday");
return crypto.subtle.sign({name: 'hmac', hash: {name: 'sha-1'}}, key, dataToSign);
}).then(function(signedData) {
alert('result of signing: ' + arrayBufferToHexString(signedData));
}).then(undefined, function() { alert('failed :(') });
//---------------------------
// Helper functions to work with arraybuffers
//---------------------------
function asciiToArrayBufferView(str) {
var chars = [];
for (var i = 0; i < str.length; ++i)
chars.push(str.charCodeAt(i));
return new Uint8Array(chars);
}
function arrayBufferToHexString(arrayBuffer) {
var bytes = new Uint8Array(arrayBuffer);
var hexBytes = [];
for (var i = 0; i < bytes.length; ++i) {
var byteString = bytes[i].toString(16);
if (byteString.length < 2)
byteString = "0" + byteString;
hexBytes.push(byteString);
}
return hexBytes.join("");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment