Skip to content
This repository has been archived by the owner on Feb 4, 2019. It is now read-only.

Basic Usage

Itay Grudev edited this page Oct 2, 2016 · 2 revisions

Symmetric encryption

Using the global instance of the Encryption class

A simple example of how this gem works:

Encryption.key = 'A very long encryption key'
data = 'secret data'
encrypted_str = Encryption.encrypt( data )
Encryption.decrypt( encrypted_str ) == data # true

Using your own instance of the Encryption class

If you need a separate instance with custom settings, different than the global Encryption instance, here is how you can do it:

encryptor = Encryption::Symmetric.new
encryptor.key = 'A very long encryption key'
data = 'secret data'
encrypted_str = encryptor.encrypt( data )
encryptor.decrypt( encrypted_str ) == data # true

Configuration

For symmetric encryption/decryption you need to set an encryption key. You can also optionally set an initialization vector and a cipher.

Encryption.key - Your encryption key
Encryption.iv # Optional - Encryption initialization vector. Defaults to the character "\0" (Optional)
Encryption.cipher # Optional - Your encryption algorithm. Defaults to aes-256-cbc (Optional)

Running openssl list-cipher-commands in the terminal or calling OpenSSL::Cipher.ciphers in Ruby, which list all available ciphers.

You can configure both the global instance and a other instances with a block like this:

Encryption.config do |e|
    e.key = 'Don't look!'
    e.iv = 'This is probably the easiest way to use OpenSSL in Ruby'
    e.cipher = 'camellia-128-ecb' # if you're feeling adventurous
end

Asymmetric encryption (public/private key encryption)

The encryption gem also provides a DSL for asymmetric encryption.

Generating keypair

keypair = Encryption::Keypair.new # Accepts two optional arguments: size = 2048, password = nil
keypair.public_key # Instance of Encryption::PublicKey
keypair.private_key # Instance of Encryption::PrivateKey
# Or you can use this shorter version
public_key, private_key = Encryption::Keypair.generate( 2048 )

# You can dump keys to string
private_key.to_s

# or export them to PEM format
private_key.to_pem

# and optionally encrypt them with a passphrase
private_key.to_pem( 'passphrase' )

Encryption::PublicKey and Encryption::PrivateKey

Both classes have the same methods:

# Import an existing key
Encryption::PrivateKey.new( filename[, password] ) # Import from file
Encryption::PrivateKey.new( string[, password] ) # Import from string

# Encrypt / Decrypt data
public_key = Encryption::PublicKey.new( 'existing key' )
public_key.encrypt( 'some secret data' )
public_key.decrypt( "some encrypted data" )

Note: You can use both the public and the private key to encrypt or decrypt data.