encrypt static method

Map<String, dynamic> encrypt(
  1. Uint8List privateKey,
  2. String password, {
  3. bool useScrypt = true,
  4. String? address,
  5. int? n,
  6. int? r,
  7. int? p,
})

Encrypts a private key using a passphrase.

Implementation

static Map<String, dynamic> encrypt(
  Uint8List privateKey,
  String password, {
  bool useScrypt = true,
  String? address,
  int? n, // Scrypt N
  int? r, // Scrypt r
  int? p, // Scrypt p
}) {
  final random = Random.secure();
  final salt = Uint8List(32);
  for (var i = 0; i < 32; i++) {
    salt[i] = random.nextInt(256);
  }

  final iv = Uint8List(16);
  for (var i = 0; i < 16; i++) {
    iv[i] = random.nextInt(256);
  }

  final passwordBytes = Uint8List.fromList(utf8.encode(password));
  Uint8List derivedKey;
  String kdfName;
  Map<String, dynamic> kdfParams;

  if (useScrypt) {
    kdfName = 'scrypt';
    final scryptN = n ?? 262144;
    final scryptR = r ?? 8;
    final scryptP = p ?? 1;
    kdfParams = {
      'dklen': 32,
      'n': scryptN,
      'r': scryptR,
      'p': scryptP,
      'salt': _toHex(salt),
    };
    derivedKey =
        Scrypt.derive(passwordBytes, salt, scryptN, scryptR, scryptP, 32);
  } else {
    kdfName = 'pbkdf2';
    final iterations = 262144;
    kdfParams = {
      'dklen': 32,
      'c': iterations,
      'prf': 'hmac-sha256',
      'salt': _toHex(salt),
    };
    derivedKey = Pbkdf2.deriveSha256(
        password: passwordBytes,
        salt: salt,
        iterations: iterations,
        keyLength: 32);
  }

  final encryptionKey = derivedKey.sublist(0, 16);
  final aes = AES(encryptionKey);
  final ciphertext = aes.ctr(privateKey, iv);

  // mac = keccak256(derivedKey[16...32] + ciphertext)
  final macData = Uint8List.fromList(derivedKey.sublist(16, 32) + ciphertext);
  final mac = Keccak256.hash(macData);

  return {
    'version': 3,
    'id': _generateUUID(random),
    'address': address?.replaceFirst('0x', '').toLowerCase(),
    'crypto': {
      'ciphertext': _toHex(ciphertext),
      'cipherparams': {'iv': _toHex(iv)},
      'cipher': 'aes-128-ctr',
      'kdf': kdfName,
      'kdfparams': kdfParams,
      'mac': _toHex(mac),
    },
  };
}