Module: SuningPay::RSA

Defined in:
lib/suning_pay/rsa.rb

Constant Summary collapse

MAX_ENCRYPT_LENGTH =

SuningPay 提供的KEY长度为2048

245
MAX_DECRYPT_LENGTH =
256

Class Method Summary collapse

Class Method Details

.decrypt_base64_msg(key, message) ⇒ Object

分段解密:解密前Base64解码



57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/suning_pay/rsa.rb', line 57

def self.decrypt_base64_msg(key, message)
  bytes_array = Base64::decode64 message

  input_length = bytes_array.length
  decryt_str, offset, i = "", 0, 0
  begin
    decryt_bytes = bytes_array[offset, MAX_DECRYPT_LENGTH]
    decryt_str << key.private_decrypt(decryt_bytes) #解密
    offset = (i += 1) * MAX_DECRYPT_LENGTH
  end while input_length - offset > 0

  decryt_str
end

.decrypt_msg(key, message) ⇒ Object

分段解密:解密前转回2进制



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/suning_pay/rsa.rb', line 26

def self.decrypt_msg(key, message)
  #bytes_array = Base64::decode64 message
  message_arr = [message]
  bytes_array = message_arr.pack("H*")

  input_length = bytes_array.length
  decryt_str, offset, i = "", 0, 0
  begin
    decryt_bytes = bytes_array[offset, MAX_DECRYPT_LENGTH]
    decryt_str << key.private_decrypt(decryt_bytes) #解密
    offset = (i += 1) * MAX_DECRYPT_LENGTH
  end while input_length - offset > 0

  decryt_str
end

.encrypt_base64_msg(key, message) ⇒ Object

分段加密:加密后Base64



43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/suning_pay/rsa.rb', line 43

def self.encrypt_base64_msg(key, message)
  bytes_array = message.unpack("C*")
  input_length = bytes_array.length
  encryt_str, offset, i = "", 0, 0
  begin
    encryt_bytes = bytes_array[offset, MAX_ENCRYPT_LENGTH]
    encryt_str << key.public_encrypt(encryt_bytes.pack("C*")) #加密
    offset = (i += 1) * MAX_ENCRYPT_LENGTH
  end while input_length - offset > 0

  Base64::strict_encode64(encryt_str)
end

.encrypt_msg(key, message) ⇒ Object

分段加密:加密后结果转16进制



11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/suning_pay/rsa.rb', line 11

def self.encrypt_msg(key, message)
  bytes_array = message.unpack("C*")
  input_length = bytes_array.length
  encryt_str, offset, i = "", 0, 0
  begin
    encryt_bytes = bytes_array[offset, MAX_ENCRYPT_LENGTH]
    encryt_str << key.public_encrypt(encryt_bytes.pack("C*")) #加密
    offset = (i += 1) * MAX_ENCRYPT_LENGTH
  end while input_length - offset > 0

  encryt_str.unpack("H*")[0].upcase
  #Base64::strict_encode64(encryt_str)
end