decrypt function

Future<String> decrypt(
  1. Map<String, dynamic> keyStore,
  2. String passphrase
)

Implementation

Future<String> decrypt(Map<String, dynamic> keyStore, String passphrase) async {
  List<int> ciphertext = numbers.hexToBytes(keyStore['crypto']['ciphertext']);
  String? kdf = keyStore['crypto']['kdf'];

  Map<String, dynamic> kdfparams = keyStore['crypto']['kdfparams'] is String
      ? json.decode(keyStore['crypto']['kdfparams'])
      : keyStore['crypto']['kdfparams'];
  var cipherparams = keyStore['crypto']["cipherparams"];
  var iv = numbers.hexToBytes(cipherparams["iv"]);

  List<int> encodedPassword = utf8.encode(passphrase);
  _KeyDerivator derivator = getDerivedKey(kdf, kdfparams);
  List<int> derivedKey = derivator.deriveKey(encodedPassword);
  List<int> macBuffer =
      derivedKey.sublist(16, 32) + ciphertext + iv + ALGO_IDENTIFIER.codeUnits;

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

  String macString = keyStore['crypto']['mac'];

  Function eq = const ListEquality().equals;
  if (!eq(mac.toUpperCase().codeUnits, macString.toUpperCase().codeUnits)) {
    throw 'Decryption Failed';
  }

  var aesKey = derivedKey.sublist(0, 16);
  var encryptedPrivateKey =
      numbers.hexToBytes(keyStore["crypto"]["ciphertext"]);

  var aes = _initCipher(false, aesKey, iv);

  var privateKeyByte = await aes.process(encryptedPrivateKey as Uint8List);
  return numbers.bytesToHex(privateKeyByte);
}