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



59
60
61
# File 'lib/crypto_laser.rb', line 59

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

.decrypt(key, base64_cipher_text) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/crypto_laser.rb', line 38

def self.decrypt(key, base64_cipher_text)
  enc_key = key[0...32]
  mac_key = key[32...64]
  cipher_text = Base64.decode64(base64_cipher_text)

  code = cipher_text[0,2]
  algorithm = CryptoLaser.algorithms[code]
  raise "Invalid algorithm code." unless algorithm

  text_to_mac = cipher_text[0...-32]
  mac = OpenSSL::HMAC.digest(OpenSSL::Digest::Digest.new('sha256'), mac_key, text_to_mac)
  raise "MAC check failed" unless mac == cipher_text[-32..-1]

  decipher = OpenSSL::Cipher.new(CryptoLaser.algorithms[code])
  decipher.decrypt
  decipher.key = enc_key
  decipher.iv = cipher_text[2...18]

  decipher.update(cipher_text[18...-32]) +  decipher.final
end

.default_algorithm_codeObject



63
64
65
# File 'lib/crypto_laser.rb', line 63

def self.default_algorithm_code
  "V1"
end

.encrypt(key, plain_text) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/crypto_laser.rb', line 19

def self.encrypt(key, plain_text)
  enc_key = key[0...32]
  mac_key = key[32...64]

  code = CryptoLaser.default_algorithm_code

  cipher = OpenSSL::Cipher.new(CryptoLaser.algorithms[code])
  cipher.encrypt
  cipher.key = enc_key
  nonce = cipher.random_iv
  cipher.iv = nonce
  cipher_text = cipher.update(plain_text) + cipher.final

  text_to_mac = code + nonce + cipher_text
  mac = OpenSSL::HMAC.digest(OpenSSL::Digest::Digest.new('sha256'), mac_key, text_to_mac)

  Base64.strict_encode64(text_to_mac + mac).chomp
end