rewrite MegolmExportEncryption using async/await

... to make it easier to add exception handling
pull/21833/head
Richard van der Hoff 2017-06-08 07:54:47 +01:00
parent 34e4d8088b
commit b16e652acc
2 changed files with 112 additions and 105 deletions

View File

@ -36,7 +36,7 @@ const subtleCrypto = window.crypto.subtle || window.crypto.webkitSubtle;
* @param {String} password * @param {String} password
* @return {Promise<String>} promise for decrypted output * @return {Promise<String>} promise for decrypted output
*/ */
export function decryptMegolmKeyFile(data, password) { export async function decryptMegolmKeyFile(data, password) {
const body = unpackMegolmKeyFile(data); const body = unpackMegolmKeyFile(data);
// check we have a version byte // check we have a version byte
@ -60,33 +60,30 @@ export function decryptMegolmKeyFile(data, password) {
const ciphertext = body.subarray(37, 37+ciphertextLength); const ciphertext = body.subarray(37, 37+ciphertextLength);
const hmac = body.subarray(-32); const hmac = body.subarray(-32);
return deriveKeys(salt, iterations, password).then((keys) => { const [aesKey, hmacKey] = await deriveKeys(salt, iterations, password);
const [aesKey, hmacKey] = keys;
const toVerify = body.subarray(0, -32); const toVerify = body.subarray(0, -32);
return subtleCrypto.verify( const isValid = await subtleCrypto.verify(
{name: 'HMAC'}, {name: 'HMAC'},
hmacKey, hmacKey,
hmac, hmac,
toVerify, toVerify,
).then((isValid) => { );
if (!isValid) { if (!isValid) {
throw new Error('Authentication check failed: incorrect password?'); throw new Error('Authentication check failed: incorrect password?');
} }
return subtleCrypto.decrypt( const plaintext = await subtleCrypto.decrypt(
{ {
name: "AES-CTR", name: "AES-CTR",
counter: iv, counter: iv,
length: 64, length: 64,
}, },
aesKey, aesKey,
ciphertext, ciphertext,
); );
});
}).then((plaintext) => { return new TextDecoder().decode(new Uint8Array(plaintext));
return new TextDecoder().decode(new Uint8Array(plaintext));
});
} }
@ -100,7 +97,7 @@ export function decryptMegolmKeyFile(data, password) {
* key-derivation function. * key-derivation function.
* @return {Promise<ArrayBuffer>} promise for encrypted output * @return {Promise<ArrayBuffer>} promise for encrypted output
*/ */
export function encryptMegolmKeyFile(data, password, options) { export async function encryptMegolmKeyFile(data, password, options) {
options = options || {}; options = options || {};
const kdfRounds = options.kdf_rounds || 500000; const kdfRounds = options.kdf_rounds || 500000;
@ -115,44 +112,42 @@ export function encryptMegolmKeyFile(data, password, options) {
// of a single bit of iv is a price we have to pay. // of a single bit of iv is a price we have to pay.
iv[9] &= 0x7f; iv[9] &= 0x7f;
return deriveKeys(salt, kdfRounds, password).then((keys) => { const [aesKey, hmacKey] = await deriveKeys(salt, kdfRounds, password);
const [aesKey, hmacKey] = keys;
return subtleCrypto.encrypt( const ciphertext = await subtleCrypto.encrypt(
{ {
name: "AES-CTR", name: "AES-CTR",
counter: iv, counter: iv,
length: 64, length: 64,
}, },
aesKey, aesKey,
new TextEncoder().encode(data), new TextEncoder().encode(data),
).then((ciphertext) => { );
const cipherArray = new Uint8Array(ciphertext);
const bodyLength = (1+salt.length+iv.length+4+cipherArray.length+32);
const resultBuffer = new Uint8Array(bodyLength);
let idx = 0;
resultBuffer[idx++] = 1; // version
resultBuffer.set(salt, idx); idx += salt.length;
resultBuffer.set(iv, idx); idx += iv.length;
resultBuffer[idx++] = kdfRounds >> 24;
resultBuffer[idx++] = (kdfRounds >> 16) & 0xff;
resultBuffer[idx++] = (kdfRounds >> 8) & 0xff;
resultBuffer[idx++] = kdfRounds & 0xff;
resultBuffer.set(cipherArray, idx); idx += cipherArray.length;
const toSign = resultBuffer.subarray(0, idx); const cipherArray = new Uint8Array(ciphertext);
const bodyLength = (1+salt.length+iv.length+4+cipherArray.length+32);
const resultBuffer = new Uint8Array(bodyLength);
let idx = 0;
resultBuffer[idx++] = 1; // version
resultBuffer.set(salt, idx); idx += salt.length;
resultBuffer.set(iv, idx); idx += iv.length;
resultBuffer[idx++] = kdfRounds >> 24;
resultBuffer[idx++] = (kdfRounds >> 16) & 0xff;
resultBuffer[idx++] = (kdfRounds >> 8) & 0xff;
resultBuffer[idx++] = kdfRounds & 0xff;
resultBuffer.set(cipherArray, idx); idx += cipherArray.length;
return subtleCrypto.sign( const toSign = resultBuffer.subarray(0, idx);
{name: 'HMAC'},
hmacKey, const hmac = await subtleCrypto.sign(
toSign, {name: 'HMAC'},
).then((hmac) => { hmacKey,
hmac = new Uint8Array(hmac); toSign,
resultBuffer.set(hmac, idx); );
return packMegolmKeyFile(resultBuffer);
}); const hmacArray = new Uint8Array(hmac);
}); resultBuffer.set(hmacArray, idx);
}); return packMegolmKeyFile(resultBuffer);
} }
/** /**
@ -163,51 +158,51 @@ export function encryptMegolmKeyFile(data, password, options) {
* @param {String} password password * @param {String} password password
* @return {Promise<[CryptoKey, CryptoKey]>} promise for [aes key, hmac key] * @return {Promise<[CryptoKey, CryptoKey]>} promise for [aes key, hmac key]
*/ */
function deriveKeys(salt, iterations, password) { async function deriveKeys(salt, iterations, password) {
const start = new Date(); const start = new Date();
return subtleCrypto.importKey( const key = await subtleCrypto.importKey(
'raw', 'raw',
new TextEncoder().encode(password), new TextEncoder().encode(password),
{name: 'PBKDF2'}, {name: 'PBKDF2'},
false, false,
['deriveBits'], ['deriveBits'],
).then((key) => { );
return subtleCrypto.deriveBits(
{
name: 'PBKDF2',
salt: salt,
iterations: iterations,
hash: 'SHA-512',
},
key,
512,
);
}).then((keybits) => {
const now = new Date();
console.log("E2e import/export: deriveKeys took " + (now - start) + "ms");
const aesKey = keybits.slice(0, 32); const keybits = await subtleCrypto.deriveBits(
const hmacKey = keybits.slice(32); {
name: 'PBKDF2',
salt: salt,
iterations: iterations,
hash: 'SHA-512',
},
key,
512,
);
const aesProm = subtleCrypto.importKey( const now = new Date();
'raw', console.log("E2e import/export: deriveKeys took " + (now - start) + "ms");
aesKey,
{name: 'AES-CTR'}, const aesKey = keybits.slice(0, 32);
false, const hmacKey = keybits.slice(32);
['encrypt', 'decrypt'],
); const aesProm = subtleCrypto.importKey(
const hmacProm = subtleCrypto.importKey( 'raw',
'raw', aesKey,
hmacKey, {name: 'AES-CTR'},
{ false,
name: 'HMAC', ['encrypt', 'decrypt'],
hash: {name: 'SHA-256'}, );
}, const hmacProm = subtleCrypto.importKey(
false, 'raw',
['sign', 'verify'], hmacKey,
); {
return Promise.all([aesProm, hmacProm]); name: 'HMAC',
}); hash: {name: 'SHA-256'},
},
false,
['sign', 'verify'],
);
return await Promise.all([aesProm, hmacProm]);
} }
const HEADER_LINE = '-----BEGIN MEGOLM SESSION DATA-----'; const HEADER_LINE = '-----BEGIN MEGOLM SESSION DATA-----';

View File

@ -81,15 +81,23 @@ describe('MegolmExportEncryption', function() {
describe('decrypt', function() { describe('decrypt', function() {
it('should handle missing header', function() { it('should handle missing header', function() {
const input=stringToArray(`-----`); const input=stringToArray(`-----`);
expect(()=>MegolmExportEncryption.decryptMegolmKeyFile(input, '')) return MegolmExportEncryption.decryptMegolmKeyFile(input, '')
.toThrow('Header line not found'); .then((res) => {
throw new Error('expected to throw');
}, (error) => {
expect(error.message).toEqual('Header line not found');
});
}); });
it('should handle missing trailer', function() { it('should handle missing trailer', function() {
const input=stringToArray(`-----BEGIN MEGOLM SESSION DATA----- const input=stringToArray(`-----BEGIN MEGOLM SESSION DATA-----
-----`); -----`);
expect(()=>MegolmExportEncryption.decryptMegolmKeyFile(input, '')) return MegolmExportEncryption.decryptMegolmKeyFile(input, '')
.toThrow('Trailer line not found'); .then((res) => {
throw new Error('expected to throw');
}, (error) => {
expect(error.message).toEqual('Trailer line not found');
});
}); });
it('should handle a too-short body', function() { it('should handle a too-short body', function() {
@ -98,8 +106,12 @@ AXNhbHRzYWx0c2FsdHNhbHSIiIiIiIiIiIiIiIiIiIiIAAAACmIRUW2OjZ3L2l6j9h0lHlV3M2dx
cissyYBxjsfsAn cissyYBxjsfsAn
-----END MEGOLM SESSION DATA----- -----END MEGOLM SESSION DATA-----
`); `);
expect(()=>MegolmExportEncryption.decryptMegolmKeyFile(input, '')) return MegolmExportEncryption.decryptMegolmKeyFile(input, '')
.toThrow('Invalid file: too short'); .then((res) => {
throw new Error('expected to throw');
}, (error) => {
expect(error.message).toEqual('Invalid file: too short');
});
}); });
it('should decrypt a range of inputs', function(done) { it('should decrypt a range of inputs', function(done) {