在 python 和 javascript 中生成 SHA256 哈希会导致不同的结果

mr_*_*rk_ 5 hash encoding cryptography cross-language cryptojs

我在加密明文时遇到问题。

我在Python中做什么:

def encrypt(plaintext):
    import hashlib, base64

    hashed = hashlib.sha256(plaintext).digest()
    return base64.b64encode(hashed)

def main():
    input_value = "a"
    output = encrypt(plaintext=input_value)
    print output

if __name__ == "__main__":
    main()
Run Code Online (Sandbox Code Playgroud)

Python 中的结果:

ypeBEsobvcr6wjGzmiPcTaeG7/gUfE5yuYB3ha/uSLs=
Run Code Online (Sandbox Code Playgroud)

我在 JS 中做什么:

ypeBEsobvcr6wjGzmiPcTaeG7/gUfE5yuYB3ha/uSLs=
Run Code Online (Sandbox Code Playgroud)

JS 中的结果:

ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb
Run Code Online (Sandbox Code Playgroud)

有谁知道我做错了什么?

或者有没有办法在两种语言中获得相同的加密结果?

顺便说一句:对我来说更改 python 代码会更容易,因为我的数据库中已经有 CryptoJS 加密的值。

Art*_* B. 6

CryptoJS 大多数情况下不会抛出错误。你正在undefined进入hashed.toString(CryptoJS.Base64);. 使用CryptoJS.enc.Base64, 因为CryptoJS.enc.Hex默认使用。

但由于您更喜欢更改 python,我建议以这种方式进行哈希处理:

def encrypt(plaintext):
    import hashlib, base64
    return hashlib.sha256(plaintext).hexdigest()
Run Code Online (Sandbox Code Playgroud)

当 CryptoJS 更改默认行为时,您仍然应该将 JavaScript 代码更改为十六进制编码。