简体   繁体   English

与 JS 和 Python 中的 sha1 不同的摘要?

[英]Different digest from sha1 in JS and Python?

I've been stuck in this for a while, for the life of me.为了我的生活,我已经被困在这个问题上一段时间了。

I have this thing in python3我在python3中有这个东西

msg = "6NmByERB9ZDJX9OKDtIzpGl8ei7KBiYI"+"\n"+"1623776851607"+"\n"+"/api2/v2/users/me"+"\n"+"0"
message = msg.encode('utf-8')
hash_object = hashlib.sha1(message)
sha_1_sign = hash_object.hexdigest()
print(sha_1_sign)
# 4ff521a9b87ddd0dea00a842f8f5d72819f9df0a

but I cannot GET THIS SAME HASH in NodeJS, I've tried a lot of solutions;但是我无法在 NodeJS 中获得相同的哈希值,我尝试了很多解决方案; at first I though it was the first part, the encode to utf-8, because printing that was returning different results, but it seems like that's not it, it was just different representation of the same string.起初我虽然它是第一部分,编码到 utf-8,因为打印返回不同的结果,但似乎不是这样,它只是同一字符串的不同表示。

My approach in JS:我在 JS 中的方法:

const crypto = require('crypto') // maybe another library that works in browser? 
const msg = "6NmByERB9ZDJX9OKDtIzpGl8ei7KBiYI"+"\n"+"1623776851607"+"\n"+"/api2/v2/users/me"+"\n"+"0"
let shasum = crypto.createHash('sha1')
shasum.update(JSON.stringify(msg))
let hashed_string = shasum.digest('hex')
console.log(hashed_string)
// c838ca6f79551d828d6e4a810bd49c1df07b54a3

thanks for any help :)谢谢你的帮助 :)

Don't JSON.stringify the message.不要JSON.stringify消息。 JSON.stringify adds double quotes at the beginning and end and it replaces all newlines (and most other whitespace characters) with two characters \\n . JSON.stringify在开头和结尾添加双引号,并用两个字符\\n替换所有换行符(和大多数其他空白字符)。 msg has length 66 and JSON.stringify(msg) has length 71. This code generates the expected SHA1 value: msg长度为 66, JSON.stringify(msg)长度为 71。此代码生成预期的 SHA1 值:

const crypto = require('crypto') // maybe another library that works in browser? 
const msg = "6NmByERB9ZDJX9OKDtIzpGl8ei7KBiYI"+"\n"+"1623776851607"+"\n"+"/api2/v2/users/me"+"\n"+"0"
let shasum = crypto.createHash('sha1')
shasum.update(msg)
let hashed_string = shasum.digest('hex')
console.log(hashed_string)

Here you can see the differences between msg and JSON.stringify(msg) :在这里你可以看到msgJSON.stringify(msg)之间的区别:

 const msg = "6NmByERB9ZDJX9OKDtIzpGl8ei7KBiYI"+"\\n"+"1623776851607"+"\\n"+"/api2/v2/users/me"+"\\n"+"0" console.log(msg) console.log(JSON.stringify(msg)); console.log(msg.length) console.log(JSON.stringify(msg).length); console.log(JSON.stringify(msg) === msg);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM