javascript - 将加密 hmac 转换为 crypto-js hmac 字符串
问题描述
我正在尝试转换一个秘密的 hmac 字符串以允许我在邮递员中测试我的 api。Postman 预装了 cryptojs。这是我在测试服务器上使用加密的过程:
const crypto = require('crypto');
const generateHmac = (privateKey, ts) => {
const hmac = crypto.createHmac('sha256', privateKey);
hmac.update(ts);
const signature = hmac.digest('hex');
return signature;
}
这与 postman 中使用 cryptojs 生成的字符串不匹配:
const createHmacString = (privateKey, ts) => {
const hmac = CryptoJS.HmacSHA256(ts, privateKey).toString(CryptoJS.enc.Hex)
return hmac;
}
不知道我在这里做错了什么。提前致谢!
解决方案
好的,终于想通了——crypto-js 不提供实际的字节,因此对所有内容进行编码都是必要的:
const createHmacString = (privateKey, ts) => {
const key = CryptoJS.enc.Utf8.parse(privateKey)
const timestamp = CryptoJS.enc.Utf8.parse(ts)
const hmac = CryptoJS.enc.Hex.stringify(CryptoJS.HmacSHA256(timestamp, key))
// const hmac = CryptoJS.HmacSHA256(ts, privateKey).toString(CryptoJS.enc.Hex)
return hmac;
}
let ts = new Date().getTime();
const signature = createHmacString("your-private-key", ts);
推荐阅读
- sqoop - 使用 sqoop 只更新 mysql 表中的一列
- javascript - 如何使用 Javascript 和 Node js 从表单传递数组
- javascript - JS 和 HTML5 入门
- sql-server - MARS TDS 标头包含错误 - ASP.NET Core + EF Core 2.1.4 + Azure SQL Server
- android - 如何在 Fragment 中覆盖 OnItemSelected 方法
- java - 本地开发最佳实践:Java、Docker、Kubernetes
- sitemap.xml - 错误:自定义站点地图结构中的名称空间不正确
- ruby - 尝试在厨师食谱中包含模块时,Ruby 返回未初始化的常量错误
- php - PHP 函数包括 -> 网站未加载
- bash - 试图解决“找不到匹配的 mac 错误”,任何想法