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.

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);
  final version = json.valueAs("version");
  if (version != 3) {
    throw const Web3SecretStorageDefinationV3Exception(
      "Unsupported secret storage version.",
    );
  }
  final crypto = json['crypto'] ?? json['Crypto'];
  if (crypto["cipher"] != "aes-128-ctr") {
    throw const Web3SecretStorageDefinationV3Exception(
      "Unsupported cypher algorithm.",
    );
  }
  final KDFParam derivator = KDFParam.fromJson(crypto);

  final encodedPassword = StringUtils.encode(password);
  final derivedKey = derivator.deriveKey(encodedPassword);
  final aesKey = 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 ArgumentException.invalidOperationArguments(
      "decode",
      name: "encoded",
      reason: "Wrong password or the data is corrupted",
    );
  }

  final iv = BytesUtils.fromHexString(crypto['cipherparams']['iv']);
  final encryptText = encryptedPrivateKey.clone();
  final List<int> data = QuickCrypto.processCtr(
    key: aesKey,
    iv: iv,
    data: encryptText,
  );
  return Web3SecretStorageDefinationV3._(
    CryptoParam.fromJson(crypto),
    encodedPassword,
    json.valueAs("id"),
    data,
  );
}