bcgit / bc-csharp

BouncyCastle.NET Cryptography Library (Mirror)
https://www.bouncycastle.org/csharp
MIT License
1.68k stars 558 forks source link

"PrivateKeyFactory. CreateKey" encountered an error "illegal object in GetInstance: Org.BouncyCastle.Asn1.DerOctetString (Parameter 'obj')” #551

Closed qq1176914912 closed 4 months ago

qq1176914912 commented 4 months ago

Hello, excuse me. I used the openssl command to generate an ec public-private key pair: image image This is the public key I got: -----BEGIN PUBLIC KEY----- MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEKOXBCs+W1aT9EgmWOded358ssRPb aZG5WZB2B4CEvpETimZ/y/h/DXakMubAW+38NbwBPkoEhzOPSO8LHabdJg== -----END PUBLIC KEY---

This is the private key I got: -----BEGIN EC PRIVATE KEY----- MHcCAQEEIElQEOIJ+xJCXVr5dOjbQmIUvqmFMF+CL1CEwo2JQxe2oAoGCCqGSM49 AwEHoUQDQgAEKOXBCs+W1aT9EgmWOded358ssRPbaZG5WZB2B4CEvpETimZ/y/h/ DXakMubAW+38NbwBPkoEhzOPSO8LHabdJg== -----END EC PRIVATE KEY-----

I decoded them through base64 and converted them to byte[], which I wanted to pass "PrivateKeyFactory. CreateKey" and "PublicKeyFactory CreateKey" two methods will be private and public keys into "AsymmetricKeyParameter" type, in the process of the public key transformation no problem. However, the private key conversion will report an error: Illegal object in GetInstance: Org. BouncyCastle. From the DerOctetString (Parameter "obj"). How do we fix this? Am I doing it the wrong way?

peterdettman commented 4 months ago

PrivateKeyFactory only handles things encoded as PrivateKeyInfo (from the PKCS#8 standard), but in this case the encoding being used is ECPrivateKey (from the SEC 1 standard).

I think you can use the openssl-pkcs8 command to convert the key format.

Alternatively, call Org.BouncyCastle.Asn1.Sec.ECPrivateKeyStructure.GetInstance instead (with the same byte[] as argument).

P.S.: in the current version ECPrivateKeyStructure doesn't really validate the format until you actually try to access 'GetKey', 'GetPublicKey', 'GetParameters'. The code has already changed so that in the next version it will validate immediately.

qq1176914912 commented 4 months ago

PrivateKeyFactory only handles things encoded as PrivateKeyInfo (from the PKCS#8 standard), but in this case the encoding being used is ECPrivateKey (from the SEC 1 standard).

I think you can use the openssl-pkcs8 command to convert the key format.

Alternatively, call Org.BouncyCastle.Asn1.Sec.ECPrivateKeyStructure.GetInstance instead (with the same byte[] as argument).

P.S.: in the current version ECPrivateKeyStructure doesn't really validate the format until you actually try to access 'GetKey', 'GetPublicKey', 'GetParameters'. The code has already changed so that in the next version it will validate immediately.

Thank you for your reply, which can solve my problem.