encryptPhrase function

Future<String> encryptPhrase(
  1. String phrase, {
  2. String? password,
  3. Map<String, dynamic>? options,
})

Implementation

Future<String> encryptPhrase(
  String phrase, {
  String? password,
  Map<String, dynamic>? options,
}) async {
  final Uint8List uuid = Uint8List(16);
  final Uuid uuidParser = const Uuid()..v4buffer(uuid);
  final String salt = randomAsHex(64);
  final List<int> iv = randomAsU8a(16);

  final String kdf = options?['kdf'] is String ? options!['kdf'] : 'scrypt';
  final int level = options?['level'] is int ? options!['level'] : 8192;
  final int n = kdf == 'pbkdf2' ? 262144 : level;

  final Map<String, dynamic> kdfParams = {
    'salt': salt,
    'n': n,
    'r': 8,
    'p': 1,
    'dklen': 32,
  };

  final deriveKeyResult = await nativeDeriveKey(
    kdf: kdf,
    iv: iv,
    message: phrase,
    useCipherText: null,
    kdfParams: kdfParams,
    passphrase: password,
    salt: (kdfParams['salt'] as String).replaceAll('0x', ''),
  );

  final Map<String, dynamic> map = {
    'crypto': {
      'cipher': 'aes-128-ctr',
      'cipherparams': {'iv': Uint8List.fromList(iv).toHex()},
      'ciphertext': Uint8List.fromList(deriveKeyResult.cipherText).toHex(),
      'kdf': kdf,
      'kdfparams': kdfParams,
      'mac': deriveKeyResult.mac,
    },
    'id': uuidParser.v4buffer(uuid),
    'version': 3,
  };
  final String result = json.encode(map);
  return result;
}