jruby / jruby-openssl

JRuby's OpenSSL gem
http://www.jruby.org
Other
45 stars 79 forks source link

Failed to read EC private key from PKCS8 PEM file #266

Closed tsaarni closed 1 year ago

tsaarni commented 1 year ago

I'm trying to read EC private key from a file:

[1] pry(main)> require "openssl"
=> true
[2] pry(main)> OpenSSL::PKey::read(File.read("example-ec-pkey.pem"))
=> #<OpenSSL::PKey::RSA:0x440461ef>

It returns RSA key which is not correct since the key is EC private key in PKCS8 PEM format. Trying to use the key for TLS will cause the authentication to fail.

Here are the version I'm using, but it seems it behaves the same in previous version of jruby-openssl as well

[3] pry(main)> puts Gem.loaded_specs["jruby-openssl"].version
0.14.0
$ jruby --version
jruby 9.3.4.0 (2.6.8) 2022-03-23 eff48c1ebf OpenJDK 64-Bit Server VM 11.0.16+8 on 11.0.16+8 +jit [x86_64-linux]

Here is the example EC private key I used.

$ cat example-ec-pkey.pem
-----BEGIN PRIVATE KEY-----
MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgUmgU1rG7E9WJmB4A
D1RZ+PP+aYEH2ZZxWTGVR0gDr/qhRANCAAR5d0hOX+W8RznN62sAzIeozl4OBl6K
nKdpKKiZTAua05NCaWJR5mGnrCyn4g+sQV4pUgmp9NzSMwmXAzJt3GK9
-----END PRIVATE KEY-----
$ openssl ec -in example-ec-pkey.pem -text -noout
read EC key
Private-Key: (256 bit)
priv:
    52:68:14:d6:b1:bb:13:d5:89:98:1e:00:0f:54:59:
    f8:f3:fe:69:81:07:d9:96:71:59:31:95:47:48:03:
    af:fa
pub:
    04:79:77:48:4e:5f:e5:bc:47:39:cd:eb:6b:00:cc:
    87:a8:ce:5e:0e:06:5e:8a:9c:a7:69:28:a8:99:4c:
    0b:9a:d3:93:42:69:62:51:e6:61:a7:ac:2c:a7:e2:
    0f:ac:41:5e:29:52:09:a9:f4:dc:d2:33:09:97:03:
    32:6d:dc:62:bd
ASN1 OID: prime256v1
NIST CURVE: P-256

it has failed with other EC keys as well, so I do not think there is anything specific in this key.

With ruby-3.1.2 and ruby openssl-3.0.0

irb(main):003:0> OpenSSL::PKey::read(File.read("example-ec-pkey.pem"))
=> #<OpenSSL::PKey::EC:0x00007f1f0e595978 oid=id-ecPublicKey>