Module: Encryptor::Public

Included in:
Person
Defined in:
lib/encryptor.rb

Instance Method Summary collapse

Instance Method Details

#aes_encrypt(txt, key) ⇒ Object


22
23
24
25
26
27
28
29
30
31
# File 'lib/encryptor.rb', line 22

def aes_encrypt(txt, key)
  cipher = OpenSSL::Cipher.new('AES-256-CBC')
  cipher.encrypt
  cipher.key = Base64.decode64 key['key']
  cipher.iv  = Base64.decode64 key['iv']
  ciphertext = ''
  ciphertext << cipher.update(txt)
  ciphertext << cipher.final
  Base64.strict_encode64(ciphertext)
end

#encrypt(cleartext) ⇒ Object


7
8
9
10
11
12
13
# File 'lib/encryptor.rb', line 7

def encrypt cleartext
  aes_key = gen_aes_key
  ciphertext = aes_encrypt(cleartext, aes_key)
  encrypted_key = encrypt_aes_key aes_key
  cipher_hash = {:aes_key => encrypted_key, :ciphertext => ciphertext}
  Base64.strict_encode64( cipher_hash.to_json )
end

#encrypt_aes_key(key) ⇒ Object


33
34
35
# File 'lib/encryptor.rb', line 33

def encrypt_aes_key key
  Base64.strict_encode64(public_key.public_encrypt( key.to_json ))
end

#gen_aes_keyObject


15
16
17
18
19
20
# File 'lib/encryptor.rb', line 15

def gen_aes_key
  cipher = OpenSSL::Cipher.new('AES-256-CBC')
  key = cipher.random_key
  iv = cipher.random_iv
  {'key' => Base64.strict_encode64(key), 'iv' => Base64.strict_encode64(iv)}
end