blob: 6927b90437b715e8013d009c33bfa363b65d17e3 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
|
# Copyright (c) 2010, Diaspora Inc. This file is
# licensed under the Affero General Public License version 3 or later. See
# the COPYRIGHT file.
module Encryptor
module Public
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.encode64( cipher_hash.to_json )
end
def gen_aes_key
cipher = OpenSSL::Cipher.new('AES-256-CBC')
key = cipher.random_key
iv = cipher.random_iv
{'key' => Base64.encode64(key), 'iv' => Base64.encode64(iv)}
end
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.encode64 ciphertext
end
def encrypt_aes_key key
Base64.encode64 public_key.public_encrypt( key.to_json )
end
end
module Private
def decrypt cipher_json
json = JSON.parse(Base64.decode64 cipher_json)
aes_key = get_aes_key json['aes_key']
aes_decrypt(json['ciphertext'], aes_key)
end
def get_aes_key encrypted_key
clear_key = encryption_key.private_decrypt( Base64.decode64 encrypted_key )
JSON::parse(clear_key)
end
def aes_decrypt(ciphertext, key)
cipher = OpenSSL::Cipher.new('AES-256-CBC')
cipher.decrypt
cipher.key = Base64.decode64 key['key']
cipher.iv = Base64.decode64 key['iv']
txt = ''
txt << cipher.update(Base64.decode64 ciphertext)
txt << cipher.final
txt
end
end
end
|