Skip to content

Instantly share code, notes, and snippets.

@kaizhu256
Last active July 17, 2019 09:06
Show Gist options
  • Save kaizhu256/c11f32c4a1ad4ad063e6df74e6ae588b to your computer and use it in GitHub Desktop.
Save kaizhu256/c11f32c4a1ad4ad063e6df74e6ae588b to your computer and use it in GitHub Desktop.
webcrypto example
var local;
local = {};
local.cryptoAesDecrypt = function (key, data, onError) {
/*
* this function will aes-256-cbc decrypt Uint8Array data with the Uint8Array key
* example usage:
key = new Uint8Array(32);
local.cryptoAesEncrypt(key, new Uint8Array([1,2,3]), function (error, data) {
console.assert(!error, error);
local.cryptoAesDecrypt(key, data, console.log);
});
*/
/*globals Uint8Array*/
var cipher, crypto, iv;
// init iv
iv = data.subarray(0, 16);
// optimization - create resized-view of data
data = data.subarray(16);
crypto = typeof window === 'object' && window.crypto;
if (!(crypto && crypto.subtle && typeof crypto.subtle.importKey === 'function')) {
setTimeout(function () {
crypto = require('crypto');
cipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
onError(null, Buffer.concat([cipher.update(data), cipher.final()]));
});
return;
}
crypto.subtle.importKey('raw', key, {
name: 'AES-CBC'
}, false, ['decrypt']).then(function (key) {
crypto.subtle.decrypt({ iv: iv, name: 'AES-CBC' }, key, data).then(function (data) {
onError(null, new Uint8Array(data));
}).catch(onError);
}).catch(onError);
};
local.cryptoAesEncrypt = function (key, data, onError) {
/*
* this function will aes-256-cbc encrypt Uint8Array data with the Uint8Array key
key = new Uint8Array(32);
local.cryptoAesEncrypt(key, new Uint8Array([1,2,3]), function (error, data) {
console.assert(!error, error);
local.cryptoAesDecrypt(key, data, console.log);
});
*/
/*globals Uint8Array*/
var cipher, crypto, iv;
// init iv
iv = new Uint8Array(16 + Math.ceil(data.length / 16) * 16);
crypto = typeof window === 'object' && window.crypto;
if (!(crypto && crypto.subtle && typeof crypto.subtle.importKey === 'function')) {
setTimeout(function () {
crypto = require('crypto');
// init iv
iv.set(crypto.randomBytes(16));
cipher = crypto.createCipheriv('aes-256-cbc', key, iv.subarray(0, 16));
data = cipher.update(data);
iv.set(data, 16);
iv.set(cipher.final(), 16 + data.length);
onError(null, iv);
});
return;
}
// init iv
iv.set(crypto.getRandomValues(new Uint8Array(16)));
crypto.subtle.importKey('raw', key, {
name: 'AES-CBC'
}, false, ['encrypt']).then(function (key) {
crypto.subtle.encrypt({
iv: iv.subarray(0, 16),
name: 'AES-CBC'
}, key, data).then(function (data) {
iv.set(new Uint8Array(data), 16);
onError(null, iv);
}).catch(onError);
}).catch(onError);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment