Last active
August 3, 2017 16:10
-
-
Save Jeanhwea/39c6fe38358e45cc423bb33c7427751b to your computer and use it in GitHub Desktop.
Generate Wechat Signature in Python
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
| #!/usr/bin/env python | |
| # -*- coding: utf-8 -*- | |
| import hashlib | |
| import random | |
| def gen_nonce(length = 16): | |
| base = 'abcdefghijklmnopqrstvuwxyzABCDEFGHIJKLMNOPQRSTVUWXYZ0123456789' | |
| chars = [base[random.randrange(0, len(base))] for _ in xrange(length)] | |
| return ''.join(chars) | |
| def gen_signature(param): | |
| sorted_kv = ['{0}={1}'.format(k, param[k]) for k in sorted(param)] | |
| sha1 = hashlib.sha1('&'.join(sorted_kv)) | |
| hashcode = sha1.hexdigest() | |
| return hashcode | |
| if __name__ == '__main__': | |
| param = { | |
| 'noncestr': 'Wm3WZYTPz0wzccnW', | |
| 'jsapi_ticket': 'sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg', | |
| 'timestamp': '1414587457', | |
| 'url': 'http://mp.weixin.qq.com?params=value' | |
| } | |
| sig = '0f9de62fce790f9a083d5c99e95740ceb90c27ed' | |
| assert gen_signature(param) == sig | |
| for i in xrange(5): | |
| print gen_nonce() | |
| # outputs: | |
| # asElkHMNuD1eIFzL | |
| # mQklM6AKcbMlPaNR | |
| # dFewKFjxe8Ci9HSP | |
| # q64jlqF74Yoa9TQp | |
| # gOzhpXerH0NunSAp |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment