|
1 | 1 | # frozen_string_literal: true |
2 | 2 |
|
3 | 3 | require 'openssl' |
| 4 | +require 'digest' |
| 5 | +require 'base64' |
4 | 6 | require 'models/client_token' |
5 | 7 |
|
6 | 8 | class EncryptionUtils |
7 | | - BLOCK_SIZE = 16 |
8 | | - KEY_SIZE = 32 |
9 | | - |
10 | | - def self.encrypt(text, cipher_key) |
11 | | - begin |
12 | | - cipher = OpenSSL::Cipher::AES.new(KEY_SIZE, :CBC).encrypt |
13 | | - cipher.padding = 0 |
14 | | - |
15 | | - if text.size % BLOCK_SIZE != 0 |
16 | | - return nil |
| 9 | + def self.padding_key(key, length) |
| 10 | + if key.length == length |
| 11 | + key |
| 12 | + else |
| 13 | + if key.length > length |
| 14 | + key.slice(0, length) |
| 15 | + else |
| 16 | + (length - key.length).times { key << '0' } |
| 17 | + key |
17 | 18 | end |
| 19 | + end |
| 20 | + end |
18 | 21 |
|
19 | | - cipher_key = Digest::SHA1.hexdigest cipher_key |
20 | | - cipher.key = cipher_key.slice(0, BLOCK_SIZE) |
21 | | - s = cipher.update(text) + cipher.final |
22 | | - |
23 | | - s.unpack('H*')[0].upcase |
| 22 | + def self.encrypt(plain_text, secret_key) |
| 23 | + begin |
| 24 | + cipher = OpenSSL::Cipher.new('aes-256-cbc') |
| 25 | + cipher.encrypt |
| 26 | + iv = cipher.random_iv |
| 27 | + cipher.key = padding_key(secret_key, 32) |
| 28 | + encrypted = cipher.update(plain_text) + cipher.final |
| 29 | + (iv + encrypted).unpack1('H*') |
24 | 30 | rescue StandardError |
25 | 31 | '' |
26 | 32 | end |
27 | 33 | end |
28 | 34 |
|
29 | | - def self.decrypt(encrypted, cipher_key) |
| 35 | + def self.decrypt(cipher_text, secret_key) |
30 | 36 | begin |
31 | | - cipher = OpenSSL::Cipher::AES.new(KEY_SIZE, :CBC).decrypt |
32 | | - cipher.padding = 0 |
33 | | - |
34 | | - cipher_key = Digest::SHA1.hexdigest cipher_key |
35 | | - cipher.key = cipher_key.slice(0, BLOCK_SIZE) |
36 | | - s = [encrypted].pack('H*').unpack('C*').pack('c*') |
37 | | - |
38 | | - rv = cipher.update(s) + cipher.final |
39 | | - rv.strip |
| 37 | + cipher = OpenSSL::Cipher.new('aes-256-cbc') |
| 38 | + cipher.decrypt |
| 39 | + raw_data = [cipher_text].pack('H*') |
| 40 | + cipher.iv = raw_data.slice(0, 16) |
| 41 | + cipher.key = padding_key(secret_key, 32) |
| 42 | + decrypted = JSON.parse(cipher.update(raw_data.slice(16, raw_data.length)) + cipher.final) |
| 43 | + |
| 44 | + return ClientToken.new(decrypted['cid'], decrypted['vid'], decrypted['fp']) |
40 | 45 | rescue StandardError |
41 | | - ClientToken.new('', '', '') |
| 46 | + ClientToken.new('', '','') |
42 | 47 | end |
43 | 48 | end |
44 | 49 | end |
0 commit comments