4

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

我在 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 加密的值。

4

1 回答 1

5

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

但是由于您更喜欢更改 python,我建议以这种方式进行散列:

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

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

于 2015-01-21T16:53:11.600 回答