Last active
August 29, 2015 14:14
-
-
Save bastengao/38b8be5c9e7dcc31c6cd to your computer and use it in GitHub Desktop.
微信公众平台企业号验证URL (处理 echostr)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'openssl' | |
require 'base64' | |
# 参考 http://qydev.weixin.qq.com/wiki/index.php?title=加解密方案的详细说明 | |
AES_KEY = 'aaaa' | |
encrypted_enchostr = 'bbbb' | |
def parse_msg(text) | |
random = text[0..16] | |
msg_len = text[16, 4].reverse.unpack('V')[0] | |
content = text[20, msg_len] | |
corp_id = text[(20+msg_len-1)..-1] | |
return content, corp_id | |
end | |
def decrypt(text) | |
decipher = OpenSSL::Cipher.new('AES-256-CBC') | |
decipher.decrypt | |
decipher.padding = 0 | |
key_data = Base64.decode64(AES_KEY) | |
decipher.key = key_data | |
decipher.iv = key_data[0..16] | |
plain = decipher.update(Base64.decode64(text)) + decipher.final | |
truncate_padding(plain) | |
end | |
def truncate_padding(plain) | |
pad = plain.bytes[-1] | |
# no padding | |
pad = 0 if pad < 1 || pad > 32 | |
plain[0...(plain.length - pad)] | |
end | |
# echostr 就是解密后 echostr 的明文内容 | |
echostr, corp_id = parse_msg(decrypt(encrypted_echostr)) | |
puts echostr |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment