Ephenodrom / Dart-Basic-Utils

A dart package for many helper methods fitting common situations
MIT License
368 stars 79 forks source link

Converting ECPrivateKey SEC1 to PCKS8 #99

Closed romgrm closed 1 year ago

romgrm commented 1 year ago

Hello !

Firstly thanks for your lib, it's really helpful !

I'm currently generating an EC keypair that I encode in PEM format.

The back end to which I send the keys tells me that they need the Pkcs8 format and not SEC1.

I've tried to do this but I get a type error during conversion : [VERBOSE-2:dart_vm_initializer.cc(41)] Unhandled Exception: type 'ASN1OctetString' is not a subtype of type 'ASN1Sequence' in type cast

The code :

var ec = CryptoUtils.generateEcKeyPair();
    var privKey = ec.privateKey as ECPrivateKey;
    var pubKey = ec.publicKey as ECPublicKey;  

    var privKeyPem = CryptoUtils.encodeEcPrivateKeyToPem(privKey);
    var pubKeyPem = CryptoUtils.encodeEcPublicKeyToPem(pubKey);

    var bytes = CryptoUtils.getBytesFromPEMString(privKeyPem);
    ECPrivateKey privateKeyFromBytes = CryptoUtils.ecPrivateKeyFromDerBytes(bytes, pkcs8: true); 

I wonder if it's possible to convert an ECPrivateKey to Pcks8? Or is it only for RSA keys?

I'm not very comfortable with all this, so I may be talking nonsense.

Thanks :)

Ephenodrom commented 1 year ago

@romgrm As far as I can see, the RFC of PKCS8 should allow EC private key to be encoded in the pkcs8 format. But this library does not support it at the moment. It only supports RSA keys to be encoded in PKCS8.

Therefore I can provide you some solutions :

I keep this issue open to close it once the feature is added.

romgrm commented 1 year ago

@Ephenodrom thanks for the answer. I try to push a PR as quickly as possible with the conversion code :)

romgrm commented 1 year ago

@Ephenodrom done here :)

Ephenodrom commented 1 year ago

PR is already merged and live on pub.dev