Class: Gibberish::RSA

Inherits:
Object
  • Object
show all
Defined in:
lib/gibberish/rsa.rb

Overview

This wraps the OpenSSL RSA functions Simply instantiate with a public key or private key

cipher = Gibberish::RSA.new(private_key)
enc = cipher.encrypt(data)
dec = cipher.decrypt(enc)

cipher = Gibberish::RSA(public_key)
cipher.decrypt(enc)

You can also generate a keypair using Gibberish::RSA.generate_keypair

kp = Gibberish::RSA.generate_keypair(4096)
kp.public_key #=> Outputs a Base64 encoded public key
kp.private_key #=> Outputs the Base64 pem

KeyPair will hand back the private key when passed to the RSA class.

cipher = Gibberish::RSA.new(kp)

OpenSSL CLI Interop

openssl rsautl -decrypt -inkey [pem_file] -in [BinaryEncodedCryptedFile]

or if you're using the default base64 output, you'll need to decode that first

openssl enc -d -base64 -in [gibberish.crypted] | \
openssl rsautl -decrypt -inkey [pem_file]

Defined Under Namespace

Classes: KeyPair

Class Method Summary (collapse)

Instance Method Summary (collapse)

Constructor Details

- (RSA) initialize(key, passphrase = nil)

Expects a public key at the minumum

Parameters:

  • (#to_s) key

    public or private

  • (String) passphrase (defaults to: nil)

    to key



78
79
80
# File 'lib/gibberish/rsa.rb', line 78

def initialize(key, passphrase=nil)
  @key = OpenSSL::PKey::RSA.new(key.to_s, passphrase)
end

Class Method Details

+ (Object) generate_keypair(bits = 2048)

Generate an RSA keypair - defaults to 2048 bits

Parameters:

  • (Integer) bits (defaults to: 2048)


69
70
71
# File 'lib/gibberish/rsa.rb', line 69

def RSA.generate_keypair(bits=2048)
  KeyPair.generate(bits)
end

Instance Method Details

- (Object) decrypt(data, opts = {})

Decrypt data using the key

Parameters:

  • (#to_s) data
  • (Hash) opts (defaults to: {})

Options Hash (opts):

  • (Boolean) :binary — default: false

    don't decode the data as Base64



102
103
104
105
106
107
108
109
# File 'lib/gibberish/rsa.rb', line 102

def decrypt(data, opts={})
  data = data.to_s
  raise "No private key set!" unless @key.private?
  unless opts[:binary]
    data = Base64.decode64(data)
  end
  @key.private_decrypt(data)
end

- (Object) encrypt(data, opts = {})

Encrypt data using the key

Parameters:

  • (#to_s) data
  • (Hash) opts (defaults to: {})

Options Hash (opts):

  • (Boolean) :binary — default: false

    encode the data in binary, not Base64



87
88
89
90
91
92
93
94
95
# File 'lib/gibberish/rsa.rb', line 87

def encrypt(data, opts={})
  data = data.to_s
  enc = @key.public_encrypt(data)
  if opts[:binary]
    enc
  else
    Base64.encode64(enc)
  end
end