Class: CryptoLaser

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

Overview

Simple library for authenticated encryption. Most of the work is done by the aead gem, which itself punts to OpenSSL.

Additional features provided by this library are:

  • Nonce management. No one knows what a nonce is, so this

    library just takes of that for you.
    
  • Base64 encoding of ciphertexts (since we want to use the

    encrypted values in config files)
    
  • The value returned by encrypt includes the nonce and

    the algorithm used to create the ciphertext (so we can
    upgrade to a stronger algorithm later if need be)
    

Class Method Summary collapse

Class Method Details

.algorithmsObject



40
41
42
# File 'lib/crypto_laser.rb', line 40

def self.algorithms
  { "V1" => 'AES-256-CBC-HMAC-SHA-256' }
end

.decrypt(key, base64_cipher_text) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
# File 'lib/crypto_laser.rb', line 28

def self.decrypt(key, base64_cipher_text)
  cipher_text = Base64.decode64(base64_cipher_text)
  code = cipher_text[0,2]
  algorithm = CryptoLaser.algorithms[code]
  raise "Invalid algorithm code." unless algorithm
  mode = AEAD::Cipher.new(algorithm)
  cipher = mode.new(key)
  nonce = cipher_text[2...18] # TODO: Base on code
  ctext = cipher_text[18..-1]
  cipher.decrypt(nonce, code, ctext)
end

.default_algorithm_codeObject



44
45
46
# File 'lib/crypto_laser.rb', line 44

def self.default_algorithm_code
  "V1"
end

.encrypt(key, plain_text) ⇒ Object



19
20
21
22
23
24
25
26
# File 'lib/crypto_laser.rb', line 19

def self.encrypt(key, plain_text)
  code = CryptoLaser.default_algorithm_code
  mode   = AEAD::Cipher.new(CryptoLaser.algorithms[code])
  cipher = mode.new(key)
  nonce = CryptoLaser.generate_nonce
  cipher_text = cipher.encrypt(nonce, code, plain_text)
  Base64.strict_encode64(code + nonce + cipher_text).chomp
end

.generate_nonceObject



48
49
50
# File 'lib/crypto_laser.rb', line 48

def self.generate_nonce
  SecureRandom.random_bytes(16)
end