Home > Software design >  Ruby OpenSSL: How to fetch just token from public key
Ruby OpenSSL: How to fetch just token from public key

Time:04-29

I am using OpenSSL::PKey::RSA.new(2048) to create public and private key..

privae_key = OpenSSL::PKey::RSA.new(2048)
public_key = private_key.public_key

Below is my public key

puts public_key.class
=> OpenSSL::PKey::RSA

puts public_key
=> -----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAywjG1X8f87fAg7yW/u7V
wPxOoR/yVAs87ew0rpcWuSKClVF8sXSuGI9LPXDVFIrBegw4zVI6PBAdKWqw6Ogv
y3KwHGD3z6AtwzQzUHvkT74zkSKcpGMSqITwAzUOjX0JbJSH0n3YBhekg3og6A G
TxZDivoa3VPsN hoW7bvai4dUDbCpeDbahLgPggVe9mc/jNc2 Ozf79lROgC4q9P
cpyQi7e4qHsZfptNU9lE3a69fI23O2MhGNtu1 ke2D GL8whXC66pXctnhPD 3 5
OC7x/dFaN7OIv44rYc7udc7lwEtHhfKIgVP8mIYai cJMfq4G Ip/nn5xwihCkUt
4QIDAQAB
-----END PUBLIC KEY-----

from the above public key i want to extract only key portion i.e i want to extract only below data from above public key in the form of string. i want to ignore header -----BEGIN PUBLIC KEY----- and footer -----END PUBLIC KEY-----

MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAywjG1X8f87fAg7yW/u7V
wPxOoR/yVAs87ew0rpcWuSKClVF8sXSuGI9LPXDVFIrBegw4zVI6PBAdKWqw6Ogv
y3KwHGD3z6AtwzQzUHvkT74zkSKcpGMSqITwAzUOjX0JbJSH0n3YBhekg3og6A G
TxZDivoa3VPsN hoW7bvai4dUDbCpeDbahLgPggVe9mc/jNc2 Ozf79lROgC4q9P
cpyQi7e4qHsZfptNU9lE3a69fI23O2MhGNtu1 ke2D GL8whXC66pXctnhPD 3 5
OC7x/dFaN7OIv44rYc7udc7lwEtHhfKIgVP8mIYai cJMfq4G Ip/nn5xwihCkUt
4QIDAQAB

Is there a way to do this? i tried all methods supported on object public_key but nothing is working.. can someone help?

CodePudding user response:

You can export the key to a string with to_pem(). This string contains the PEM encoded key, i.e. header, Base64 encoded body with line breaks, and footer. Header and footer can then be removed with sub():

require "openssl"

private_key = OpenSSL::PKey::RSA.new(2048)
public_key = private_key.public_key

pem = public_key.to_pem
pem.sub! "-----BEGIN PUBLIC KEY-----\n", ''
pem.sub! "\n-----END PUBLIC KEY-----", ''
#pem.gsub! "\n", '' # remove all remaining linebreaks

puts pem.class
puts pem

Possible output:

String
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmTbDL1Tqz83QPvQ8cbFp
GWIXk5ukTX0E18PHY//3GaSF0xMLGBx6KeGprCpJbhUGcxFQi2/Hdr9BAjaqDwF6
89Bo2CHW5wU4HL0IgcahrfcpZGlggMEbEpKH6boppt6XZuppAAkxBprHVkJ951Ve
TK3tqpO8i4x9t5JuJteSbb67ts2IOXbi/YGUOassby3y4Q286YCYZh5VXHMLdKKJ
qHgICUn1dlAMI7ie0n4s1ESnkqo9GXgWAy3WrJTUsX/FK97 8h b1aa0qnHbwWpp
dxNxExdUUEgBGHKz4piVwTJ9gfQu4hSQpcVstUgjDx6qTo9HSu4iQi1FPKxZG0lN
xwIDAQAB

Alternatively, the key can be exported with to_der() and the result Base64 encoded.

  • Related