Web3SecretStorageDefinationV3.decode constructor

Web3SecretStorageDefinationV3.decode(
  1. String encoded,
  2. String password, {
  3. SecretWalletEncoding encoding = SecretWalletEncoding.json,
})

Factory method to decode and create a Web3SecretStorageDefinationV3 from an encoded string and a password.

  • encoded: The encoded string containing wallet data.
  • password: The password used to derive the encryption key.

Returns a Web3SecretStorageDefinationV3 instance decoded from the input data, or throws an error if decoding or password validation fails.

Implementation

factory Web3SecretStorageDefinationV3.decode(String encoded, String password,
    {SecretWalletEncoding encoding = SecretWalletEncoding.json}) {
  if (encoding == SecretWalletEncoding.cbor) {
    return _decodeCbor(encoded, password);
  }
  final json = _toJsonEcoded(encoded, encoding: encoding);

  if (json['version'] != 3) {
    throw const Web3SecretStorageDefinationV3Exception(
        "Library only supports version 3");
  }
  final crypto = json['crypto'] ?? json['Crypto'];
  final KDFParam derivator = KDFParam.fromJson(crypto);

  final encodedPassword = List<int>.from(StringUtils.encode(password));
  final derivedKey = derivator.deriveKey(encodedPassword);
  final aesKey = List<int>.from(derivedKey.sublist(0, 16));
  final List<int> macBytes = derivedKey.sublist(16, 32);
  final encryptedPrivateKey = BytesUtils.fromHexString(crypto["ciphertext"]);
  final derivedMac = CryptoParam._mac(macBytes, encryptedPrivateKey);
  if (derivedMac != crypto["mac"]) {
    throw const Web3SecretStorageDefinationV3Exception(
        "Wrong password or the file is corrupted");
  }
  if (crypto["cipher"] != "aes-128-ctr") {
    throw Web3SecretStorageDefinationV3Exception("Invalid Cypher.",
        details: {"excepted": "aes-128-ctr", "cipher": crypto["cipher"]});
  }
  final iv = BytesUtils.fromHexString(crypto['cipherparams']['iv']);
  final encryptText = List<int>.from(encryptedPrivateKey);
  final List<int> data =
      QuickCrypto.processCtr(key: aesKey, iv: iv, data: encryptText);
  return Web3SecretStorageDefinationV3._(
      CryptoParam.fromJson(json['crypto'] ?? json['Crypto']),
      encodedPassword,
      json["id"],
      data);
}