|
1 | 1 | # frozen_string_literal: true |
2 | 2 |
|
3 | 3 | require 'openssl' |
| 4 | +require 'models/client_token' |
4 | 5 |
|
5 | 6 | class EncryptionUtils |
6 | 7 | BLOCK_SIZE = 16 |
7 | 8 | KEY_SIZE = 32 |
8 | 9 |
|
9 | 10 | def self.encrypt(text, cipher_key) |
10 | | - cipher = OpenSSL::Cipher::AES.new(KEY_SIZE, :CBC).encrypt |
11 | | - cipher.padding = 0 |
| 11 | + begin |
| 12 | + cipher = OpenSSL::Cipher::AES.new(KEY_SIZE, :CBC).encrypt |
| 13 | + cipher.padding = 0 |
12 | 14 |
|
13 | | - if text.size % BLOCK_SIZE != 0 |
14 | | - return nil |
15 | | - end |
| 15 | + if text.size % BLOCK_SIZE != 0 |
| 16 | + return nil |
| 17 | + end |
16 | 18 |
|
17 | | - cipher_key = Digest::SHA1.hexdigest cipher_key |
18 | | - cipher.key = cipher_key.slice(0, BLOCK_SIZE) |
19 | | - s = cipher.update(text) + cipher.final |
| 19 | + cipher_key = Digest::SHA1.hexdigest cipher_key |
| 20 | + cipher.key = cipher_key.slice(0, BLOCK_SIZE) |
| 21 | + s = cipher.update(text) + cipher.final |
20 | 22 |
|
21 | | - s.unpack('H*')[0].upcase |
| 23 | + s.unpack('H*')[0].upcase |
| 24 | + rescue StandardError |
| 25 | + '' |
| 26 | + end |
22 | 27 | end |
23 | 28 |
|
24 | 29 | def self.decrypt(encrypted, cipher_key) |
25 | | - cipher = OpenSSL::Cipher::AES.new(KEY_SIZE, :CBC).decrypt |
26 | | - cipher.padding = 0 |
27 | | - |
28 | | - cipher_key = Digest::SHA1.hexdigest cipher_key |
29 | | - cipher.key = cipher_key.slice(0, BLOCK_SIZE) |
30 | | - s = [encrypted].pack('H*').unpack('C*').pack('c*') |
31 | | - |
32 | | - rv = cipher.update(s) + cipher.final |
33 | | - rv.strip |
| 30 | + 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 |
| 40 | + rescue StandardError |
| 41 | + ClientToken.new('', '', '') |
| 42 | + end |
34 | 43 | end |
35 | 44 | end |
0 commit comments