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

78.57% Statements 11/14
0% Branches 0/2
50% Functions 1/2
84.61% Lines 11/13

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 373x 3x 3x 3x 3x 3x       3x 7x 7x 7x 7x                                              
import { getCryptoLib } from 'micro-stacks/crypto-aes';
import { ensureUint8Array, utf8ToBytes } from 'micro-stacks/common';
import { NodeCryptoPbkdf2 } from './node';
import { WebCryptoPbkdf2 } from './web';
import { pbkdf2Async } from '@noble/hashes/pbkdf2';
import { sha512 } from '@noble/hashes/sha512';
 
import type { Pbkdf2, Pbkdf2Digests } from './types';
 
export async function createPbkdf2(): Promise<Pbkdf2> {
  try {
    const cryptoLib = await getCryptoLib();
    Iif (cryptoLib.name === 'webCrypto') return new WebCryptoPbkdf2(cryptoLib.lib);
    return new NodeCryptoPbkdf2(cryptoLib.lib.pbkdf2);
  } catch (_e) {
    return {
      derive(
        password: string,
        salt: Uint8Array,
        iterations: number,
        keyLength: number,
        _digest: Pbkdf2Digests = 'sha512'
      ): Promise<Uint8Array> {
        return pbkdf2Async(
          sha512,
          ensureUint8Array(utf8ToBytes(password)),
          ensureUint8Array(salt),
          {
            c: iterations,
            dkLen: keyLength,
          }
        );
      },
    };
  }
}