bcgit / pc-dart

Pointy Castle - Dart Derived Bouncy Castle APIs
MIT License
233 stars 122 forks source link

Invalid RSA Public key PEM PKCS1 #168

Closed itzikkle closed 1 year ago

itzikkle commented 2 years ago

hi, im using RSA (2048) encryption. after creating public and private keys, i create a PEM from both of them. when i check the public key created - its not a valid PEM. what am i doing wrong?

String encodePublicKeyToPemPKCS1(RSAPublicKey publicKey) { var topLevel = ASN1Sequence();

topLevel.add(ASN1Integer(publicKey.modulus!));
topLevel.add(ASN1Integer(publicKey.exponent!));
var dataBase64 = base64.encode(topLevel.encodedBytes);
return """-----BEGIN RSA PUBLIC KEY-----\r\n$dataBase64\r\n-----END RSA PUBLIC KEY-----""";

the created invalid PEN for example:

"-----BEGIN RSA PUBLIC KEY----- MIIBCgKCAQEAiBtJ53RbFUtZYc1hKWbO7gQqt40g+AIkxB0/n8bGq85et+A0E+GxCTltuEWIIrLAaP0LRG73o5aqimBiOnGHYXKEEz9bMsQWFYwmmOM4NgySIK3sPS6tnXcYZwax9dfcwTKTyRvJE0SFf/uRgY3rjX7CvH8MrXrLImrfNYVrrnMCLuf6ehGu5yk4PNHKbksyrG4GKeOcUEpss7atdH5SZHqZ3GWADHw7xBrpR9Djg+/nVbJGJgXznT6q0SadGceD320eWVVZ2qUoXHDgjgdXz/Wg3YMZdDANBb67bExxWMpidOKK0pGKfA5IhIMfOTSZ3RpsyiBeDzBix0dulNWe/wIDAQAB -----END RSA PUBLIC KEY-----"

Ephenodrom commented 2 years ago

I recommend to check out my package at https://github.com/Ephenodrom/Dart-Basic-Utils and take a look at the implementation in the class CryptoUtils.

 static String encodeRSAPublicKeyToPemPkcs1(RSAPublicKey rsaPublicKey) {
    var topLevelSeq = ASN1Sequence();
    topLevelSeq.add(ASN1Integer(rsaPublicKey.modulus));
    topLevelSeq.add(ASN1Integer(rsaPublicKey.exponent));

    var dataBase64 = base64.encode(topLevelSeq.encode());
    var chunks = StringUtils.chunk(dataBase64, 64);

    return '$BEGIN_RSA_PUBLIC_KEY\n${chunks.join('\n')}\n$END_RSA_PUBLIC_KEY';
  }

But it seems to match your code. So the ASN1 structure looks fine. Maybe the line breaks are a problem. Which software says that the PEM format is invalid ?

The ASN1 dump from your PEM :

SEQUENCE (2 elem)
  INTEGER (2048 bit) 171818660289524392253368288767583411073307274799442050758256828176946…
  INTEGER 65537