Convert privateKey to PKCS#8 format in Dart
357
This code work for me. Thanks Topaco
https://raw.githubusercontent.com/Ephenodrom/Dart-Basic-Utils/master/lib/src/CryptoUtils.dart
https://raw.githubusercontent.com/Ephenodrom/Dart-Basic-Utils/master/lib/src/StringUtils.dart
Author by
Felix A Marrero Pentón
Updated on January 04, 2023Comments
-
Felix A Marrero Pentón over 1 year
In FLUTTER - DART using RSA algoritm i get a privateKey. I have this method for encode privateKey to PEM in PKCS#1 format but i need a method for encode the privateKey to PKCS#8 format. I can't finde nothing in internet for that.
Uint8List _encodePrivateKeyToPemPKCS1(RSAPrivateKey privateKey) { var topLevel = new ASN1Sequence(); var version = ASN1Integer(BigInt.from(0)); var modulus = ASN1Integer(privateKey.n!); var publicExponent = ASN1Integer(privateKey.exponent!); var privateExponent = ASN1Integer(privateKey.privateExponent!); var p = ASN1Integer(privateKey.p!); var q = ASN1Integer(privateKey.q!); var dP = privateKey.privateExponent! % (privateKey.p! - BigInt.from(1)); var exp1 = ASN1Integer(dP); var dQ = privateKey.privateExponent! % (privateKey.q! - BigInt.from(1)); var exp2 = ASN1Integer(dQ); var iQ = privateKey.q!.modInverse(privateKey.p!); var co = ASN1Integer(iQ); topLevel.add(version); topLevel.add(modulus); topLevel.add(publicExponent); topLevel.add(privateExponent); topLevel.add(p); topLevel.add(q); topLevel.add(exp1); topLevel.add(exp2); topLevel.add(co); return topLevel.encodedBytes; }
-
Topaco about 2 yearsThis code generates a PEM encoded private key in PKCS#8 from an
RSAPrivateKey
object. Not tested, so you should check the generated key, e.g. withopenssl rsa -check
. -
Maarten Bodewes about 2 yearsPlease indicate if it has worked or not, you can answer your own question if it does.
-
Topaco about 2 yearsFor newer PointyCastle versions, see these links to the updated code: gist.github.com/proteye/…, in particular
CryptoUtils.encodeRSAPrivateKeyToPem()
-