mirror of
https://github.com/bitwarden/browser
synced 2025-12-17 16:53:34 +00:00
stub out crypto function service with pbkdf2
This commit is contained in:
3
src/abstractions/cryptoFunction.service.ts
Normal file
3
src/abstractions/cryptoFunction.service.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export abstract class CryptoFunctionService {
|
||||
pbkdf2: (password: Buffer, salt: Buffer, iterations: number, length: number) => Promise<ArrayBuffer>
|
||||
}
|
||||
17
src/services/nodeCryptoFunction.service.ts
Normal file
17
src/services/nodeCryptoFunction.service.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import * as crypto from 'crypto';
|
||||
|
||||
import { CryptoFunctionService } from '../abstractions/cryptoFunction.service';
|
||||
|
||||
export class NodeCryptoFunctionService implements CryptoFunctionService {
|
||||
async pbkdf2(password: Buffer, salt: Buffer, iterations: number, length: number): Promise<ArrayBuffer> {
|
||||
return new Promise<ArrayBuffer>((resolve, reject) => {
|
||||
crypto.pbkdf2(password, salt, iterations, length, 'sha256', (error, key) => {
|
||||
if (error != null) {
|
||||
reject(error);
|
||||
} else {
|
||||
resolve(key.buffer);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
42
src/services/webCryptoFunction.service.ts
Normal file
42
src/services/webCryptoFunction.service.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import * as forge from 'node-forge';
|
||||
|
||||
import { CryptoFunctionService } from '../abstractions/cryptoFunction.service';
|
||||
import { PlatformUtilsService } from '../abstractions/platformUtils.service';
|
||||
|
||||
export class WebCryptoFunctionService implements CryptoFunctionService {
|
||||
private crypto: Crypto;
|
||||
private subtle: SubtleCrypto;
|
||||
|
||||
constructor(private win: Window, private platformUtilsService: PlatformUtilsService) {
|
||||
this.crypto = win.crypto;
|
||||
this.subtle = win.crypto.subtle;
|
||||
}
|
||||
|
||||
async pbkdf2(password: Buffer, salt: Buffer, iterations: number, length: number): Promise<ArrayBuffer> {
|
||||
const importedKey = await this.subtle.importKey('raw', password, { name: 'PBKDF2' },
|
||||
false, ['deriveKey', 'deriveBits']);
|
||||
|
||||
const alg: Pbkdf2Params = {
|
||||
name: 'PBKDF2',
|
||||
salt: salt,
|
||||
iterations: iterations,
|
||||
hash: { name: 'SHA-256' },
|
||||
};
|
||||
|
||||
const keyType: AesDerivedKeyParams = {
|
||||
name: 'AES-CBC',
|
||||
length: length,
|
||||
};
|
||||
|
||||
const derivedKey = await this.subtle.deriveKey(alg, importedKey, keyType, true, ['encrypt', 'decrypt']);
|
||||
return await this.subtle.exportKey('raw', derivedKey);
|
||||
}
|
||||
|
||||
async sha1(value: Buffer): Promise<ArrayBuffer> {
|
||||
if (this.platformUtilsService.isEdge()) {
|
||||
return new Uint8Array([1]).buffer; // TODO: sha1 with forge
|
||||
} else {
|
||||
return await this.subtle.digest({ name: 'SHA-1' }, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user