All files / src/crypto-extras/crypto-pbkdf2 web.ts

18.18% Statements 2/11
0% Branches 0/4
0% Functions 0/2
18.18% Lines 2/11

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 463x     3x                                                                                    
import { utf8ToBytes } from 'micro-stacks/common';
import { Pbkdf2, Pbkdf2Digests } from './types';
 
export class WebCryptoPbkdf2 implements Pbkdf2 {
  webCrypto: Crypto;
 
  constructor(webCrypto: Crypto) {
    this.webCrypto = webCrypto;
  }
 
  async derive(
    password: string,
    salt: Uint8Array,
    iterations: number,
    keyLength: number,
    digest: Pbkdf2Digests
  ): Promise<Uint8Array> {
    let algo: string;
    if (digest === 'sha256') {
      algo = 'SHA-256';
    } else if (digest === 'sha512') {
      algo = 'SHA-512';
    } else {
      throw new Error(`Unsupported Pbkdf2 digest algorithm "${digest}"`);
    }
    const key = await this.webCrypto.subtle.importKey(
      'raw',
      utf8ToBytes(password),
      'PBKDF2',
      false,
      ['deriveBits']
    );
    const result: ArrayBuffer = await this.webCrypto.subtle.deriveBits(
      {
        name: 'PBKDF2',
        salt,
        iterations,
        hash: { name: algo },
      },
      key,
      keyLength * 8
    );
    return new Uint8Array(result);
  }
}