mirror of
https://github.com/bitwarden/browser
synced 2025-12-16 08:13:42 +00:00
password generation service to ts
This commit is contained in:
@@ -8,6 +8,55 @@ const AnalyticsIds = {
|
||||
};
|
||||
|
||||
export default class UtilsService {
|
||||
static extendObject(...objects: any[]): any {
|
||||
for (let i = 1; i < objects.length; i++) {
|
||||
for (const key in objects[i]) {
|
||||
if (objects[i].hasOwnProperty(key)) {
|
||||
objects[0][key] = objects[i][key];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return objects[0];
|
||||
}
|
||||
|
||||
// EFForg/OpenWireless
|
||||
// ref https://github.com/EFForg/OpenWireless/blob/master/app/js/diceware.js
|
||||
static secureRandomNumber(min: number, max: number): 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
|
||||
|
||||
// Create byte array and fill with N random numbers
|
||||
const byteArray = new Uint8Array(bytesNeeded);
|
||||
window.crypto.getRandomValues(byteArray);
|
||||
|
||||
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 UtilsService.secureRandomNumber(min, max);
|
||||
}
|
||||
|
||||
// Return an integer that falls within the range
|
||||
return min + rval;
|
||||
}
|
||||
|
||||
static fromB64ToArray(str: string): Uint8Array {
|
||||
const binaryString = window.atob(str);
|
||||
const bytes = new Uint8Array(binaryString.length);
|
||||
|
||||
Reference in New Issue
Block a user