ecPublicKeyFromDerBytes static method

ECPublicKey ecPublicKeyFromDerBytes(
  1. Uint8List bytes
)

Decode the given bytes into an ECPublicKey.

Implementation

static ECPublicKey ecPublicKeyFromDerBytes(Uint8List bytes) {
  var asn1Parser = ASN1Parser(bytes);
  var topLevelSeq = asn1Parser.nextObject() as ASN1Sequence;

  var algorithmIdentifierSequence = topLevelSeq.elements![0] as ASN1Sequence;
  var curveNameOi = algorithmIdentifierSequence.elements!.elementAt(1)
  as ASN1ObjectIdentifier;
  var curveName;
  var data = ObjectIdentifiers.getIdentifierByIdentifier(
      curveNameOi.objectIdentifierAsString);
  if (data != null) {
    curveName = data['readableName'];
  }

  var subjectPublicKey = topLevelSeq.elements![1] as ASN1BitString;
  var compressed = false;
  var pubBytes = subjectPublicKey.valueBytes!;
  if (pubBytes.elementAt(0) == 0) {
    pubBytes = pubBytes.sublist(1);
  }

  // Looks good so far!
  var firstByte = pubBytes.elementAt(0);
  if (firstByte != 4) {
    compressed = true;
  }
  var x = pubBytes.sublist(1, (pubBytes.length / 2).round());
  var y = pubBytes.sublist(1 + x.length, pubBytes.length);
  var params = ECDomainParameters(curveName);
  var bigX = decodeBigIntWithSign(1, x);
  var bigY = decodeBigIntWithSign(1, y);
  var pubKey = ECPublicKey(
      ecc_fp.ECPoint(
          params.curve as ecc_fp.ECCurve,
          params.curve.fromBigInteger(bigX) as ecc_fp.ECFieldElement?,
          params.curve.fromBigInteger(bigY) as ecc_fp.ECFieldElement?,
          compressed),
      params);
  return pubKey;
}