encodeEcPrivateKeyToPem static method
Enode the given elliptic curve publicKey to PEM format.
This is descripted in tools.ietf.org/html/rfc5915
ECPrivateKey ::= SEQUENCE {
version INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1),
privateKey OCTET STRING
parameters [0] ECParameters {{ NamedCurve }} OPTIONAL
publicKey [1] BIT STRING OPTIONAL
}
As descripted in the mentioned RFC, all optional values will always be set.
Implementation
static String encodeEcPrivateKeyToPem(ECPrivateKey ecPrivateKey) {
var outer = ASN1Sequence();
var version = ASN1Integer(BigInt.from(1));
var privateKeyAsBytes = encodeBigInt(ecPrivateKey.d);
var privateKey = ASN1OctetString(octets: privateKeyAsBytes);
var choice = ASN1Sequence(tag: 0xA0);
choice.add(
ASN1ObjectIdentifier.fromName(ecPrivateKey.parameters!.domainName));
var publicKey = ASN1Sequence(tag: 0xA1);
var subjectPublicKey = ASN1BitString(
stringValues: ecPrivateKey.parameters!.G.getEncoded(false));
publicKey.add(subjectPublicKey);
outer.add(version);
outer.add(privateKey);
outer.add(choice);
outer.add(publicKey);
var dataBase64 = base64.encode(outer.encode());
var chunks = _chunk(dataBase64, 64);
return '$BEGIN_EC_PRIVATE_KEY\n${chunks.join('\n')}\n$END_EC_PRIVATE_KEY';
}