decodeSecp256r1PrivateKeyPkcs8 static method

Secp256r1Pkcs8Key decodeSecp256r1PrivateKeyPkcs8(
  1. List<int> der
)

Implementation

static Secp256r1Pkcs8Key decodeSecp256r1PrivateKeyPkcs8(List<int> der) {
  final root = DerReader(der).readNode();
  _expectTag(root, DerTag.sequence, 'PrivateKeyInfo SEQUENCE');
  final fields = root.children();
  if (fields.length < 3) {
    throw CoreErrors.cryptoFailed(
      "decodeSecp256r1PrivateKeyPkcs8",
      reason: 'Malformed PrivateKeyInfo',
    );
  }

  _expectTag(fields[0], DerTag.integer, 'version');

  final algId = fields[1];
  _expectTag(algId, DerTag.sequence, 'AlgorithmIdentifier');
  final algFields = algId.children();
  if (algFields.isEmpty) {
    throw CoreErrors.cryptoFailed(
      "decodeSecp256r1PrivateKeyPkcs8",
      reason: 'Malformed AlgorithmIdentifier',
    );
  }
  _expectTag(algFields[0], DerTag.oid, 'algorithm OID');
  final algOid = DerUtils.decodeOid(algFields[0].value);
  if (algOid != Oids.ecPublicKey) {
    throw CoreErrors.cryptoFailed(
      "decodeSecp256r1PrivateKeyPkcs8",
      reason: 'Not an EC key (algorithm OID $algOid)',
    );
  }
  if (algFields.length > 1 && algFields[1].tag == DerTag.oid) {
    final curveOid = DerUtils.decodeOid(algFields[1].value);
    if (curveOid != Oids.secp256r1) {
      throw CoreErrors.cryptoFailed(
        "decodeSecp256r1PrivateKeyPkcs8",
        reason: 'Not a secp256r1 key (curve OID $curveOid)',
      );
    }
  }

  _expectTag(fields[2], DerTag.octetString, 'privateKey');
  final sec1 = decodeSecp256r1PrivateKeySec1(fields[2].value);
  return Secp256r1Pkcs8Key.from(
    privateKey: sec1.privateKey,
    publicKeyPoint: sec1.publicKeyPoint,
  );
}