Class: CryptoLaser

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

Overview

The heavy lifting is done by Ruby’s OpenSSL, so we use AES-256-CBC as the cipher and HMAC-SHA-256 as the MAC. These algorithms should be available on all Ruby 1.9 installations (including those on OS X, Windows, and Linux).

Instance Method Summary collapse

Constructor Details

#initialize(key) ⇒ CryptoLaser

Returns a new instance of CryptoLaser.



20
21
22
23
# File 'lib/crypto_laser.rb', line 20

def initialize(key)
  @enc_key = key[0...32]
  @mac_key = key[32...64]
end

Instance Method Details

#decrypt(base64_cipher_text) ⇒ Object



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

def decrypt(base64_cipher_text)
  cipher_text = Base64.decode64(base64_cipher_text)

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

  mac = mac(cipher_text[0...-32])
  raise "MAC check failed" unless equal_macs(mac, cipher_text[-32..-1])

  cipher = OpenSSL::Cipher.new(algorithm)
  cipher.decrypt
  cipher.key = @enc_key
  cipher.iv = cipher_text[2...18]

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

#encrypt(plain_text) ⇒ Object



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

def encrypt(plain_text)
  code = default_algorithm_code

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

  text_to_mac = code + iv + cipher_text
  mac = mac(text_to_mac)

  Base64.strict_encode64(text_to_mac + mac).chomp
end