Invalid public keys when using the Ruby OpenSSL library

I am trying to create RSA keypairs in Ruby, mainly using examples from this blog post . Here is my slightly modified code:

def generate_keypair(passphrase)
   rsa_key = OpenSSL::PKey::RSA.new(2048)
   cipher =  OpenSSL::Cipher::Cipher.new('aes-256-cbc')
   private_key = rsa_key.to_pem(cipher, passphrase)
   public_key = rsa_key.public_key.to_pem
   return private_key, public_key
end

This successfully generates the private key and public key, and I can write them to files in the file system.

irb(main):002:0> private_key1, public_key1 = generate_keypair('test')
[...output of keys...]
irb(main):003:0> File.open("key.pem","w") {|f| f.write(private_key1) }
=> 1766
irb(main):004:0> File.open("pubkey.pem","w") {|f| f.write(public_key1) }
=> 426

However, OpenSSL complains when I try to use this public key:

$ openssl rsautl -encrypt -inkey pubkey.pem -pubin -in text.txt -out text.ssl
unable to load Public Key

If I use a tool opensslto extract the public key from the private key, then everything works:

$ openssl rsa -in key.pem -pubout -out pubkey2.pem
Enter pass phrase for key.pem:
writing RSA key
$ openssl rsautl -encrypt -inkey pubkey2.pem -pubin -in text.txt -out text.ssl
$ openssl rsautl -decrypt -inkey key.pem -in text.ssl 
Enter pass phrase for key.pem:
this is a 
file that
needs to be
encrypted

The public key generated by the Ruby OpenSSL library is different from the public key that the opensslcli tool extracts from the private key:

$ cat pubkey.pem 
-----BEGIN RSA PUBLIC KEY-----
MIIBCgKCAQEAzgNcsEL7yGBoLBYBXFYrDL6oLP8ZbW9+VwdoXyNG6Qt/NEhEx4Ww
5yOxtXAbqeUwyvbTUxRrJ02dQcb4FGcSMDgz2QHIZyCuDJkgC9Wj7KI1Q7g0GV+7
DcZvLcwPZOhLXqUzlcZXjDWM1PZ+az734qEribgyI+87LB8TujG8v5iOvdzT/Je4
JAllToZVGC3RddfTc6ww37gB39B++FYNzPg+nrIEU45KgEWPo2eJxBpX29lACh6q
EEBCQr9xyLxOC2eomYIl3dG2dV7nGGH7Pur2HjppgJphBvNkwxIWUa/pD6hAnOQ4
MkDDFGwWv7eJLb4UZuZjafTbqokHved3bwIDAQAB
-----END RSA PUBLIC KEY-----

$ cat pubkey2.pem 
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzgNcsEL7yGBoLBYBXFYr
DL6oLP8ZbW9+VwdoXyNG6Qt/NEhEx4Ww5yOxtXAbqeUwyvbTUxRrJ02dQcb4FGcS
MDgz2QHIZyCuDJkgC9Wj7KI1Q7g0GV+7DcZvLcwPZOhLXqUzlcZXjDWM1PZ+az73
4qEribgyI+87LB8TujG8v5iOvdzT/Je4JAllToZVGC3RddfTc6ww37gB39B++FYN
zPg+nrIEU45KgEWPo2eJxBpX29lACh6qEEBCQr9xyLxOC2eomYIl3dG2dV7nGGH7
Pur2HjppgJphBvNkwxIWUa/pD6hAnOQ4MkDDFGwWv7eJLb4UZuZjafTbqokHved3
bwIDAQAB
-----END PUBLIC KEY-----

, , , Ruby OpenSSL pem . - ?

+3
1

, OSSL . "openssl rsa", RSA_PUBKEY: PUBKEY, ASN.1 - "" ( OID), , RSA. Ruby - "" RSA ( , RSA, PEM).

OSSL API, ​​ PEM_write_bio_RSA_PUBKEY ( PEM_write_bio_PUBKEY), / PEM_write_bio_RSAPublicKey.

+3

Source: https://habr.com/ru/post/1784297/


All Articles