Class: JPSClient::AES

Inherits:
Object
  • Object
show all
Defined in:
lib/jpsclient/utils/aes.rb

Overview

独立的 AES 加密解密类

Constant Summary collapse

CIPHER =
'AES-128-ECB'

Instance Method Summary collapse

Constructor Details

#initialize(key) ⇒ AES

Returns a new instance of AES.



9
10
11
12
# File 'lib/jpsclient/utils/aes.rb', line 9

def initialize(key)
  @key = key
  validate_key!
end

Instance Method Details

#decrypt(encrypted_text) ⇒ Object

解密字符串



29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/jpsclient/utils/aes.rb', line 29

def decrypt(encrypted_text)
  return nil if encrypted_text.nil? || encrypted_text.empty?

  cipher = OpenSSL::Cipher.new(CIPHER)
  cipher.decrypt
  cipher.key = @key

  decoded = Base64.strict_decode64(encrypted_text)
  cipher.update(decoded) + cipher.final
rescue => e
  raise ExceptionError, "解密失败: #{e.message}"
end

#encrypt(plain_text) ⇒ Object

加密字符串



15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/jpsclient/utils/aes.rb', line 15

def encrypt(plain_text)
  return nil if plain_text.nil? || plain_text.empty?

  cipher = OpenSSL::Cipher.new(CIPHER)
  cipher.encrypt
  cipher.key = @key

  encrypted = cipher.update(plain_text) + cipher.final
  Base64.strict_encode64(encrypted)
rescue => e
  raise ExceptionError, "加密失败: #{e.message}"
end