Skip to content

Instantly share code, notes, and snippets.

@dealloc
Last active May 2, 2017 17:49
Show Gist options
  • Save dealloc/ab9b4933f81cd1517667a792f88b0ada to your computer and use it in GitHub Desktop.
Save dealloc/ab9b4933f81cd1517667a792f88b0ada to your computer and use it in GitHub Desktop.
simple AES en/decryption
export default class Cryptor {
constructor() {
this.AES_ALGO = 'AES-CBC';
this.DERIVE_ALGO = 'PBKDF2';
this.HASH_ALGO = 'SHA-256';
this.KEY_BITS = 256;
this.KEY_ITERATIONS = 1000;
}
encrypt(data, password) {
const iv = Cryptor.generateIV();
return this.deriveKey(password).then(key => crypto.subtle.encrypt({
name: this.AES_ALGO,
iv,
}, key, Cryptor.stringToArrayBuffer(data)))
.then(encrypted => Cryptor.joinArrays(iv, new Uint8Array(encrypted)));
}
decrypt(data, password) {
const iv = data.slice(0, 16);
const payload = data.slice(16);
return this.deriveKey(password).then(key => crypto.subtle.decrypt({
name: this.AES_ALGO,
iv,
}, key, payload))
.then(decrypted => Cryptor.arrayBufferToString(new Uint8Array(decrypted)));
}
deriveKey(password) {
return crypto.subtle.importKey(
'raw',
Cryptor.stringToArrayBuffer(password),
{ name: this.DERIVE_ALGO },
false,
['deriveKey'])
.then(baseKey => crypto.subtle.deriveKey(
{
name: this.DERIVE_ALGO,
salt: Cryptor.stringToArrayBuffer('THIS IS THE SALT'),
iterations: this.KEY_ITERATIONS,
hash: this.HASH_ALGO,
},
baseKey,
{ name: this.AES_ALGO, length: this.KEY_BITS },
true,
['encrypt', 'decrypt']));
}
static generateIV(length = 16) {
return crypto.getRandomValues(new Uint8Array(length));
}
static joinArrays(arrayA, arrayB) {
const buffer = new Uint8Array(arrayA.length + arrayB.length);
buffer.set(arrayA);
buffer.set(arrayB, arrayA.length);
return buffer;
}
// buffer convertion methods
static stringToArrayBuffer(string) {
const encoder = new TextEncoder('utf-8');
return encoder.encode(string);
}
static arrayBufferToString(buffer) {
const decoder = new TextDecoder('utf-8');
return decoder.decode(buffer);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment