1
0
mirror of https://github.com/bitwarden/browser synced 2025-12-18 09:13:33 +00:00

refactor utils service to utils

This commit is contained in:
Kyle Spearrin
2018-04-23 13:03:47 -04:00
parent 5e7115f78d
commit 0fa9fc58eb
16 changed files with 168 additions and 250 deletions

View File

@@ -355,6 +355,42 @@ export class CryptoService implements CryptoServiceAbstraction {
macBytes != null ? macBytes.buffer : null, key);
}
// EFForg/OpenWireless
// ref https://github.com/EFForg/OpenWireless/blob/master/app/js/diceware.js
async randomNumber(min: number, max: number): Promise<number> {
let rval = 0;
const range = max - min + 1;
const bitsNeeded = Math.ceil(Math.log2(range));
if (bitsNeeded > 53) {
throw new Error('We cannot generate numbers larger than 53 bits.');
}
const bytesNeeded = Math.ceil(bitsNeeded / 8);
const mask = Math.pow(2, bitsNeeded) - 1;
// 7776 -> (2^13 = 8192) -1 == 8191 or 0x00001111 11111111
// Fill a byte array with N random numbers
const byteArray = new Uint8Array(await this.cryptoFunctionService.randomBytes(bytesNeeded));
let p = (bytesNeeded - 1) * 8;
for (let i = 0; i < bytesNeeded; i++) {
rval += byteArray[i] * Math.pow(2, p);
p -= 8;
}
// Use & to apply the mask and reduce the number of recursive lookups
// tslint:disable-next-line
rval = rval & mask;
if (rval >= range) {
// Integer out of acceptable range
return this.randomNumber(min, max);
}
// Return an integer that falls within the range
return min + rval;
}
// Helpers
private async aesEncrypt(plainValue: ArrayBuffer, key: SymmetricCryptoKey): Promise<EncryptedObject> {