Skip to content

Commit

Permalink
New signature module introduce.
Browse files Browse the repository at this point in the history
  • Loading branch information
Eric-Guo committed Sep 6, 2015
1 parent a41a6e3 commit 6a925af
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 15 deletions.
22 changes: 7 additions & 15 deletions lib/action_controller/responder.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
require 'English'
require 'wechat/signature'

module Wechat
module Responder
Expand Down Expand Up @@ -106,20 +107,11 @@ def verify_signature

msg_encrypt = params[:echostr] || request_content

dev_msg_signature = content_to_verify(self.class.token, params[:timestamp], params[:nonce], msg_encrypt)

render text: 'Forbidden', status: 403 if signature != Digest::SHA1.hexdigest(dev_msg_signature)
end

def content_to_verify(token, timestamp, nonce, msg_encrypt)
array = [token, timestamp, nonce]

# 默认使用明文方式验证, 企业号验证加密签名
if params[:signature].blank? && params[:msg_signature]
array << msg_encrypt
end

array.compact.collect(&:to_s).sort.join
render text: 'Forbidden', status: 403 if signature != Signature.hexdigest(self.class.encrypt_mode,
self.class.token,
params[:timestamp],
params[:nonce],
msg_encrypt)
end

def post_xml
Expand Down Expand Up @@ -164,7 +156,7 @@ def process_response(response)
end

def gen_msg(encrypt, timestamp, nonce)
msg_sign = Digest::SHA1.hexdigest [self.class.token, timestamp, nonce, encrypt].compact.collect(&:to_s).sort.join
msg_sign = Signature.hexdigest(self.class.encrypt_mode, self.class.token, timestamp, nonce, encrypt)

{ Encrypt: encrypt,
MsgSignature: msg_sign,
Expand Down
10 changes: 10 additions & 0 deletions lib/wechat/signature.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
module Wechat
module Signature
def self.hexdigest(encrypt_mode, token, timestamp, nonce, msg_encrypt)
array = [token, timestamp, nonce]
array << msg_encrypt if encrypt_mode
dev_msg_signature = array.compact.collect(&:to_s).sort.join
Digest::SHA1.hexdigest(dev_msg_signature)
end
end
end

0 comments on commit 6a925af

Please sign in to comment.