我想使用Forge创建SHA256哈希。我的测试使用文件中的二进制数据"\x01\x02\x03\x04\x05\x06\x07\x08"
。这将在Linux shell上使用sha256sum生成SHA256:
66840dda154e8a113c31dd0ad32f7f3a366a80e8136979d8f5a101d3d29d6f72
然后我使用Web加密API(crypto.subtle.digest()
)来计算哈希。我在这里从Uint8Array使用ArrayBuffer。仍然可以,计算相同的哈希值:
let data = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
const digest = await crypto.subtle.digest('SHA-256', data.buffer);
const array = Array.from(new Uint8Array(digest));
const hex = array.map(byte => ('00' + byte.toString(16)).slice(-2)).join('');
// 66840dda154e8a113c31dd0ad32f7f3a366a80e8136979d8f5a101d3d29d6f72
现在,我想使用Forge库来计算哈希值,但我无法获取它来生成正确的哈希值:
let data = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
const md = forge.md.sha256.create();
md.update(data);
let hex = md.digest().toHex();
// 181e2276640163cbb29a50fa846412edb6489b3c73e82ca4b64ae114b752a542
let data = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
const md = forge.md.sha256.create();
let buffer = forge.util.createBuffer(data);
md.update(buffer);
let hex = md.digest().toHex();
// 1d4e1124c22199ab44fc3acb57e2f68f18bee390d8a52d62b15c23d3fc157846
如何使用Forge从二进制数据创建SHA256哈希?
确定,我在issue on Github中找到了解决方案:
let data = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
const md = forge.md.sha256.create();
let buffer = String.fromCharCode.apply(null, data); // <-- HERE
md.update(buffer);
let hex = md.digest().toHex();
// 66840dda154e8a113c31dd0ad32f7f3a366a80e8136979d8f5a101d3d29d6f72