我有两个脚本来生成一个带有明文消息和Base64编码密钥的SHA256 HMAC。一个是用PHP编写的,另一个是用JavaScript编写的。PHP脚本返回正确的HMAC,但由于某些原因,JS版本没有。是什么导致了这种情况?
以下是代码示例,其中包含一个经过编辑(本质上仍然相似)的键。
This script, returns MTYxNDExNzczNzQ2NztFdXcwQ1l0bTBTMkdIdnZ2ZnN2ZGFkTEFDMGVPbVlJeHFzZk9PQWExS1BzPQ==
JS
async function hash_hmac(type, message, key, base64) {
const getUtf8Bytes = str =>
new Uint8Array(
[...unescape(encodeURIComponent(str))].map(c => c.charCodeAt(0))
);
const keyBytes = getUtf8Bytes(key);
const messageBytes = getUtf8Bytes(message);
const cryptoKey = await crypto.subtle.importKey(
"raw", keyBytes, { name: "HMAC", hash: type },
true, ["sign"]
);
const sig = await crypto.subtle.sign("HMAC", cryptoKey, messageBytes);
const data = String.fromCharCode(...new Uint8Array(sig));
return base64 ? btoa(data) : data;
}
(async function() {
let key = "YdkQZp9Pq0OsKT5TlFzrgry7j1nw0XEmbNFm86zNU3+XFEmM/I+WxrAZE7yjFAD3iWJTQ10VN2+JK3fz4b3Viw==";
let message = "1614117737467myJSON.json" + '{"json_data": "to-be-encoded"}';
let hmac = await hash_hmac("SHA-256", message, atob(key), true);
console.log(
btoa("1614117737467;" + hmac)
);
})();
Which returns MTYxNDExNzczNzQ2NztBeGxFRVJCTzVYWm5KN2ZHNCtoeWlxalJ0VmxZQmJpekNUSEwzcldMQVhzPQ==
Why are these seemingly identical scripts returning different results?
发布于 2021-02-24 13:15:41
这与在php/javascript中处理二进制数组或字符串的不同有关。如果你改变了base64_decode($key)
至$key
(php)和atob(key)
至key
(javascript)它工作得很好。
编辑:
错误在unescape(encodeURIComponent(str))
,只需删除函数并更改为str
它应该是有效的。
https://stackoverflow.com/questions/66342138
复制相似问题