Module: Wechat::Cipher
Constant Summary collapse
- BLOCK_SIZE =
32
- CIPHER =
'AES-256-CBC'
Instance Method Summary collapse
- #decrypt(msg, encoding_aes_key) ⇒ Object
- #encrypt(plain, encoding_aes_key) ⇒ Object
- #pack(content, app_id) ⇒ Object
- #program_decrypt(encrypted_data, iv, session_key) ⇒ Object
- #unpack(msg) ⇒ Object
Instance Method Details
#decrypt(msg, encoding_aes_key) ⇒ Object
23 24 25 26 27 28 29 30 31 32 33 34 |
# File 'app/apis/wechat/cipher.rb', line 23 def decrypt(msg, encoding_aes_key) cipher = OpenSSL::Cipher.new(CIPHER) cipher.decrypt cipher.padding = 0 key_data = Base64.decode64(encoding_aes_key + '=') cipher.key = key_data cipher.iv = [key_data].pack('H*') plain = cipher.update(msg) + cipher.final decode_padding(plain) end |
#encrypt(plain, encoding_aes_key) ⇒ Object
11 12 13 14 15 16 17 18 19 20 21 |
# File 'app/apis/wechat/cipher.rb', line 11 def encrypt(plain, encoding_aes_key) cipher = OpenSSL::Cipher.new(CIPHER) cipher.encrypt cipher.padding = 0 key_data = Base64.decode64(encoding_aes_key + '=') cipher.key = key_data cipher.iv = [key_data].pack('H*') cipher.update(plain) + cipher.final end |
#pack(content, app_id) ⇒ Object
49 50 51 52 53 54 55 |
# File 'app/apis/wechat/cipher.rb', line 49 def pack(content, app_id) random = SecureRandom.hex(8) text = content.force_encoding('ASCII-8BIT') msg_len = [text.length].pack('N') encode_padding("#{random}#{msg_len}#{text}#{app_id}") end |
#program_decrypt(encrypted_data, iv, session_key) ⇒ Object
36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'app/apis/wechat/cipher.rb', line 36 def program_decrypt(encrypted_data, iv, session_key) cipher = OpenSSL::Cipher.new('AES-128-CBC') cipher.decrypt cipher.key = Base64.decode64(session_key) cipher.iv = Base64.decode64(iv) decrypted_data = Base64.decode64(encrypted_data) JSON.parse(cipher.update(decrypted_data) + cipher.final) rescue Exception => e { errcode: 41003, errmsg: e. } end |
#unpack(msg) ⇒ Object
57 58 59 60 61 62 63 64 |
# File 'app/apis/wechat/cipher.rb', line 57 def unpack(msg) msg = decode_padding(msg) msg_len = msg[16, 4].reverse.unpack('V')[0] content = msg[20, msg_len] app_id = msg[(20 + msg_len)..-1] [content, app_id] end |