-
Notifications
You must be signed in to change notification settings - Fork 9
Basic Usage
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
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
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
The encryption
gem also provides a DSL for asymmetric encryption.
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' )
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.