Search code examples
encodinghashcryptographycryptojscross-language

Generating a SHA256 hash in python and javascript leads to different results


I have a problem with encrypting plaintext.

What i am doing in 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()

Result in Python:

ypeBEsobvcr6wjGzmiPcTaeG7/gUfE5yuYB3ha/uSLs=

What I am doing in JS:

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

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

alert(result);

Result in JS:

ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb

Does anyone have an idea what I am doing wrong?

Or is there a way to get the same encryption result in both languages?

By the way: It would be easier for me to change the python code, because I already have CryptoJS-encrypted values in my database.


Solution

  • CryptoJS mostly doesn't throw errors. You're passing undefined into hashed.toString(CryptoJS.Base64);. Use CryptoJS.enc.Base64, because CryptoJS.enc.Hex is used by default.

    But since you prefer to change python, I would suggest to do the hashing this way:

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

    You should still change the JavaScript code to hex encoding for when CryptoJS changes the default behavior.