Module: WeixinRailsMiddleware::Prpcrypt

Extended by:
Prpcrypt
Included in:
Prpcrypt
Defined in:
lib/weixin_rails_middleware/helpers/prpcrypt.rb

Instance Method Summary collapse

Instance Method Details

#decrypt(aes_key, text, app_id) ⇒ Object

对密文进行解密. text 需要解密的密文



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/weixin_rails_middleware/helpers/prpcrypt.rb', line 9

def decrypt(aes_key, text, app_id)
  status = 200
  text   = Base64.decode64(text)
  text   = handle_cipher(:decrypt, aes_key, text)
  result = PKCS7Encoder.decode(text)
  content  = result[16...result.length]
  len_list = content[0...4].unpack("N")
  xml_len  = len_list[0]
  xml_content = content[4...4 + xml_len]
  from_app_id = content[xml_len + 4...content.size]
  # TODO: refactor
  if app_id != from_app_id
    Rails.logger.debug("#{__FILE__}:#{__LINE__} Failure because app_id != from_app_id")
    status = 401
  end
  [xml_content, status]
end

#encrypt(aes_key, text, app_id) ⇒ Object

加密



28
29
30
31
32
33
34
35
36
# File 'lib/weixin_rails_middleware/helpers/prpcrypt.rb', line 28

def encrypt(aes_key, text, app_id)
  text    = text.force_encoding("ASCII-8BIT")
  random  = SecureRandom.hex(8)
  msg_len = [text.length].pack("N")
  text    = "#{random}#{msg_len}#{text}#{app_id}"
  text    = PKCS7Encoder.encode(text)
  text    = handle_cipher(:encrypt, aes_key, text)
  Base64.encode64(text)
end