【问题标题】:Generating a SHA256 hash in python and javascript leads to different results在 python 和 javascript 中生成 SHA256 哈希会导致不同的结果
【发布时间】:2015-01-21 15:37:17
【问题描述】:

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

我在 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()

Python 中的结果:

ypeBEsobvcr6wjGzmiPcTaeG7/gUfE5yuYB3ha/uSLs=

我在 JS 中做什么:

var result = '';
var plaintext = 'a';

if(plaintext != null && plaintext != undefined) {
    var hashed = CryptoJS.SHA256(plaintext);
    result = hashed.toString(CryptoJS.Base64);
}

alert(result);

在 JS 中的结果:

ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb

有人知道我做错了什么吗?

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

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

【问题讨论】:

  • 感谢您的评论。这只是我的代码中的复制和粘贴错误。它应该是“输出=加密(纯文本=输入值)”

标签: encoding hash cryptography cryptojs cross-language


【解决方案1】:

CryptoJS 大多不会抛出错误。您将undefined 传递给hashed.toString(CryptoJS.Base64);。使用CryptoJS.enc.Base64,因为默认使用CryptoJS.enc.Hex

但是由于您更喜欢更改 python,我建议您进行散列 this way:

def encrypt(plaintext):
    import hashlib, base64
    return hashlib.sha256(plaintext).hexdigest()

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

【讨论】:

  • 另外,由于他说他更愿意更改 Python 代码,他可以使用 .hexdigest() 而不是进行 base64 编码。
  • 谢谢,贴完答案才注意到这句话。
  • 感谢您的回答!这对我帮助很大!现在我必须弄清楚我是否会修补我的数据库或更改 python 代码。你会推荐什么?
  • @gimlithedwarf 这很难回答。有太多的可能性。如果您需要空间,您可以将其转换为 Base64 并在此列中节省约 33% 的空间。如果您曾经将此作为 URL 参数发送,则应将其保留为十六进制或将其转换为 Base64 的 URL 安全版本(RFC 4648 中的表 2)。
猜你喜欢
  • 2019-03-03
  • 2023-02-23
  • 2016-12-15
  • 2021-08-22
  • 2020-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-05
相关资源
最近更新 更多