您现在的位置是: 首页 > 后端开发 > Python Python 钉钉加签 HmacSHA256 算法签名
Python 钉钉加签 HmacSHA256 算法签名
2020-05-20 【Python】 3284人已围观 6560次浏览
简介Python 钉钉加签 HmacSHA256 算法签名
在处理钉钉机器人发送消息时,涉及到了HmacSHA256算法签名,官方文档中,只提供了Java的签名计算代码示例
下面是Python的实现,虽然已经有很多类似的SDK集成了,具体的实现还是记录下,便于学习研究
import hmac
import hashlib
import base64
import re
import time
import urllib
# secret:密钥,机器人安全设置页面,加签一栏下面显示的SEC开头的字符串,例如:SECxxxxxxxx
secret = 'SECxxxxxxxx'
# timestamp:当前时间戳,单位是毫秒,与请求调用时间误差不能超过1小时
timestamp = int(round(time.time() * 1000))
# 加密,获取sign和timestamp
data = (str(timestamp) + '\n' + secret).encode('utf-8')
secret = secret.encode('utf-8') # 使用HmacSHA256算法计算签名,然后进行Base64 encode signature = base64.b64encode(hmac.new(secret, data, digestmod=hashlib.sha256).digest())
reg = re.compile(r"'(.*)'") signature = str(re.findall(reg, str(signature))[0]) # 最后进行urlEncode urlencode = urllib.parse.quote_plus(signature)
print(urlencode)
最后输出的就是最终的签名字符串,与官方文档中的Java签名代码示例输出结果相等(以上代码在本地Python 3.7.4下正常运行,其他版本需要自己测试下)
PS:在urlEncode时,默认情况下使用 quote_plus() 函数,它将空格被编码为 ‘+’ 字符,而“/”字符被编码为 %2F,它遵循GET请求(application/x-www-form-urlencoded)的标准
urllib.parse.quote(string, safe=’/’, encoding=None, errors=None)
可以作为备用的函数是 quote(),它将空格编码为 %20,字母,数字和 ‘_.-‘字符不被编码,而“/”字符被默认为安全字符不被编码。
很赞哦! (0)
点击排行
- Error in execution; nested exception is io.lettuce.core.RedisCommandExecutionException: ERR DISABLE You can't write or read against a disable instance
- Debian apt 使用国内镜像
- RocketMQ 出现 sendDefaultImpl call timeout 问题
- 类 BASE64Decoder 程序包 sun.misc 找不到符号
- SpringBoot @NotBlank 不生效问题
- 记一次 Mybatis-Plus 自动填充无效问题解决
- nuxt 项目完整部署方案
- SpringBoot 2.x 文件上传出现 The field file exceeds its maximum permitted size of 1048576 bytes
站长推荐
猜你喜欢
- 在更新python时出现dyld: Library not loaded: /usr/local/opt/libpsl/lib/libpsl.5.dylib,Reason: image not found错误解决方案
- 查看MySQL默认读取的配置文件
- mysql 索引过长1071-max key length is 767 byte
- 优化 Mac 上 office 软件更新慢的问题
- Error in execution; nested exception is io.lettuce.core.RedisCommandExecutionException: ERR DISABLE You can't write or read against a disable instance
- Vue 监听回车 el-input 和 input 使用方法不同
- Docker 批量操作命令
- 删除Git仓库所有历史提交记录,成为一个干净的仓库
- CentOS 安装Node.js
- SpringBoot 2.x 文件上传出现 The field file exceeds its maximum permitted size of 1048576 bytes