parsePrivateKey static method

ECPrivateKey parsePrivateKey(
  1. String base64Key
)

Parses a Base64-encoded private key in PKCS#8 or SEC1 format and returns an ECPrivateKey object.

base64Key - The Base64-encoded private key string.

Throws ArgumentError if the private key format is invalid.

Implementation

static ECPrivateKey parsePrivateKey(String base64Key) {
  String cleanedBase64Key = base64Key
      .replaceAll('-----BEGIN EC PRIVATE KEY-----', '')
      .replaceAll('-----END EC PRIVATE KEY-----', '')
      .replaceAll(RegExp(r'\s+'), '')
      .replaceAll(' ', '');

  /// Decode the Base64 key
  final keyBytes = base64.decode(cleanedBase64Key);

  /// Parse the ASN.1 structure
  final asn1Parser = ASN1Parser(keyBytes);
  final topLevelSeq = asn1Parser.nextObject() as ASN1Sequence;

  if (topLevelSeq.elements.length == 3) {
    /// PKCS#8 format
    final privateKeyOctets =
        (topLevelSeq.elements[2] as ASN1OctetString).octets;
    final privateKeyParser = ASN1Parser(privateKeyOctets);
    final pkSeq = privateKeyParser.nextObject() as ASN1Sequence;

    final privateKeyInt =
        (pkSeq.elements[1] as ASN1Integer).valueAsBigInteger;
    final curve = ECCurve_secp256r1();
    return ECPrivateKey(privateKeyInt, curve);
  } else if (topLevelSeq.elements.length == 4) {
    /// SEC1 format
    final privateKeyBytes =
        (topLevelSeq.elements[1] as ASN1OctetString).octets;
    final privateKeyInt = BigInt.parse(
      privateKeyBytes.map((e) => e.toRadixString(16).padLeft(2, '0')).join(),
      radix: 16,
    );
    final curve = ECCurve_secp256r1();
    return ECPrivateKey(privateKeyInt, curve);
  } else {
    throw ArgumentError('Invalid private key format');
  }
}