nativeDeriveKey function

Future<NativeDeriveKeyResult> nativeDeriveKey({
  1. required String kdf,
  2. required List<int> iv,
  3. required String? message,
  4. required Uint8List? useCipherText,
  5. required Map<String, dynamic> kdfParams,
  6. required String salt,
  7. String? passphrase,
})

Implementation

Future<NativeDeriveKeyResult> nativeDeriveKey({
  required String kdf,
  required List<int> iv,
  required String? message,
  required Uint8List? useCipherText,
  required Map<String, dynamic> kdfParams,
  required String salt,
  String? passphrase,
}) async {
  passphrase ??= '';
  final Uint8List derivedKey;
  final Uint8List leftBits;
  final Uint8List rightBits;

  if (kdf == 'scrypt') {
    final scryptKey = await scryptDeriveKey(
      req: ScriptDeriveReq(
        n: kdfParams['n'],
        p: kdfParams['p'],
        r: kdfParams['r'],
        salt: salt.toU8a(),
        password: passphrase.plainToU8a(),
      ),
    );

    leftBits = scryptKey.leftBits;
    rightBits = scryptKey.rightBits;
    derivedKey = Uint8List.fromList(
      [...scryptKey.leftBits, ...scryptKey.rightBits],
    );
  } else {
    final scryptKey = await pbkdf2DeriveKey(
      req: PBKDFDeriveReq(
        c: 262144,
        password: passphrase.plainToU8a(),
        salt: salt.toU8a(),
      ),
    );
    leftBits = scryptKey.leftBits;
    rightBits = scryptKey.rightBits;
    derivedKey = Uint8List.fromList(
      [...scryptKey.leftBits, ...scryptKey.rightBits],
    );
  }

  final List<int> cipherText = useCipherText?.toList() ??
      await _encryptPhraseAsync(
        key: Uint8List.fromList(leftBits),
        iv: Uint8List.fromList(iv),
        message: message!,
      );

  final List<int> macBuffer =
      rightBits + cipherText + iv + _algoIdentifier.codeUnits;

  final String mac = SHA256()
      .update(Uint8List.fromList(derivedKey))
      .update(macBuffer)
      .digest()
      .toHex();

  return NativeDeriveKeyResult(
    cipherText: cipherText,
    mac: mac,
    leftBits: leftBits,
    rightBits: rightBits,
    derivedKey: derivedKey,
  );
}