encodePrivateKeyToPlainPemPKCS8 method
Plain PKCS8 private key format:
PrivateKeyInfo ::= SEQUENCE {
version Version,
privateKeyAlgorithm AlgorithmIdentifier {{PrivateKeyAlgorithms}},
privateKey PrivateKey,
attributes [0] Attributes OPTIONAL
}
Version ::= INTEGER {v1(0)} (v1,...)
PrivateKey ::= OCTET STRING
Implementation
String encodePrivateKeyToPlainPemPKCS8() {
final pkcs1 = encodePrivateKeyToPemPKCS1();
final lines = pkcs1.split('\n');
final pkcs1Body = lines.sublist(1, lines.length - 1).join('');
final pkcs1BodyBytes = base64Decode(pkcs1Body);
final algorithmIdentifierSequence = ASN1Sequence()
..add(
ASN1ObjectIdentifier('1.2.840.113549.1.1.1'
.split('.')
.map((e) => int.parse(e))
.toList()),
);
final privateKeyInfoSequence = ASN1Sequence();
final privateKeyInfoVersion = ASN1Integer.fromInt(0);
final privateKeyInfoAlgorithm = algorithmIdentifierSequence;
final pKey = ASN1OctetString(pkcs1BodyBytes);
privateKeyInfoSequence.add(privateKeyInfoVersion);
privateKeyInfoSequence.add(privateKeyInfoAlgorithm);
privateKeyInfoSequence.add(pKey);
final pkcs8Body = base64Encode(privateKeyInfoSequence.encodedBytes);
return '-----BEGIN PRIVATE KEY-----\n$pkcs8Body\n-----END PRIVATE KEY-----';
}