首页 > 解决方案 > Python 和 JavaScript 中的哈希 sha1

问题描述

我在 Python 中做了一个脚本,它是:

hashed_string = hashlib.sha1(str(string_to_hash).encode('utf-8')).hexdigest()

它可以按我的意愿工作,但我不知道如何在 JavaScript 中做到这一点。我在 JS 中做到了这一点:

const crypto = require('crypto') 
let shasum = crypto.createHash('sha1') 
let hashed_string = shasum.update(JSON.stringify(string_to_hash).digest('hex'))

但结果不一样。

标签: javascriptpythonhashsha1

解决方案


您在hash.update( )内调用hash.digest( ) ,但需要在之后调用digest()update()

例如

const crypto = require('crypto') 
let shasum = crypto.createHash('sha1')
shasum.update(JSON.stringify(string_to_hash)) 
let hashed_string = shasum.digest('hex'))

或者

const crypto = require('crypto') 
let shasum = crypto.createHash('sha1')
let hashed_string = shasum.update(JSON.stringify(string_to_hash)).digest('hex'))

或者

const crypto = require('crypto') 
let hashed_string = crypto.createHash('sha1').update(JSON.stringify(string_to_hash)).digest('hex'))

如果您在 Python 中使用与该方法返回的字符串完全相同的字符串,JSON.stringify()您将获得相同的结果。任何额外的字符都会影响结果。

例如,这里是SHA1一些类似字符串的生成哈希。

#1: {a:1,b:2}          // ca681fb779d3b6f82af9b243c480ce4fb07e7af4
#2: {a:1, b:2}         // 6327727c37c8d1893d9e341453dd1b8c7e72ffe8
#3: {"a":1,"b":2}      // 4acc71e0547112eb432f0a36fb1924c4a738cb49
#4: {"a":1, "b":2}     // 98e0e65ec27728cd01356be19e354d92fb2f4b46
#5: {"a":"1", "b":"2"} // a89dd0ae872ef448a6ddafc23b0752b799fe0de1

Javascript:

d = {a:1, b:2}  // Simple object
JSON.stringify(d) // {"a":1,"b":2} : #3 Above

Python:

d = {"a":1, "b":2}
str(d)
"{'a': 1, 'b': 2}"

在 Python 中创建的字符串使用单引号并使用额外的空格字符进行格式化,因此生成的哈希值将不同。

#6: {'a': 1, 'b': 2} // 326a92518b2b2bd864ff2d88eab7c12ca44d3fd3

推荐阅读