Friday, January 6, 2017

How to Encrypt/Decrypt Using An RSA Keypair In Ruby

Simple process:
require 'openssl'

#Import your private/public keypair into separate objects to play with
priv = OpenSSL::PKey::RSA.new(File.read('test1.priv'))
pub = OpenSSL::PKey::RSA.new(File.read('test1.pub'))

#Use your public key to encrypt some data
#Here, 3 means use no padding (I needed it for some testing)
#Here I used 56bit keys and no padding which is why my input plaintext must be 56bits (7 characters)
#If you want the default of PKCS#1 padding, just remove the '3' argument
crypted = pub.public_encrypt("123456\n", 3)

#Now decrypt using your private key object (must supply same padding as before, or leave off for default)
decrypted = priv.private_decrypt(crypted,3)

Above I created the .priv and .pub using the following openssl commands:

#I chose 56 bits for testing, if used in reality it should be much higher like 2048
openssl genrsa -out test1.priv 56

#Using your private key, create a public key
openssl rsa -in test1.priv -out test1.pub -outform PEM -pubout

No comments:

Post a Comment