encrypt function

Future<String> encrypt(
  1. String privateKey,
  2. String passphrase, [
  3. Map<String, dynamic>? options
])

Implementation

Future<String> encrypt(String privateKey, String passphrase,
    [Map<String, dynamic>? options]) async {
  Uint8List uuid = new Uint8List(16);

  String salt = crypto.randomHex(64);
  List<int> iv = crypto.randomBytes(16);
  String? kdf = 'scrypt';
  int? level = 8192;
  int? n = kdf == 'pbkdf2' ? 262144 : level;
  if (options == null) {
    kdf = 'scrypt';
    level = 8192;
    n = kdf == 'pbkdf2' ? 262144 : level;
  } else {
    kdf = options['kdf'] is String ? options['kdf'] : 'scrypt';
    level = options['level'] is int ? options['level'] : 8192;
    n = kdf == 'pbkdf2' ? 262144 : level!;
  }

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

  List<int> encodedPassword = utf8.encode(passphrase);
  _KeyDerivator derivator = getDerivedKey(kdf, kdfParams);
  List<int> derivedKey = derivator.deriveKey(encodedPassword);

  List<int> ciphertextBytes = await _encryptPrivateKey(
      derivator, encodedPassword as Uint8List, iv as Uint8List, privateKey);

  List<int> macBuffer = derivedKey.sublist(16, 32) +
      ciphertextBytes +
      iv +
      ALGO_IDENTIFIER.codeUnits;

  String mac = numbers.bytesToHex(
      new HMAC(sha256, derivedKey).update(macBuffer).digest().bytes);

  Map<String, dynamic> map = {
    'crypto': {
      'cipher': 'aes-128-ctr',
      'cipherparams': {'iv': numbers.bytesToHex(iv)},
      'ciphertext': numbers.bytesToHex(ciphertextBytes),
      'kdf': kdf,
      'kdfparams': json.encode(kdfParams),
      'mac': mac,
    },
    'id': Uuid.unparse(uuid),
    'version': 3,
  };
  String result = json.encode(map);
  return result;
}