3

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.

Artjom B.
  • 58,311
  • 24
  • 111
  • 196
mr_5p4rk_
  • 31
  • 1
  • 6
  • Thanks for the comment. That was simply a copy & paste error from my code. It should be "output = encrypt(plaintext=input_value)" – mr_5p4rk_ Jan 21 '15 at 17:04

1 Answers1

4

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.

Artjom B.
  • 58,311
  • 24
  • 111
  • 196
  • 1
    Alternately, since he said he would prefer to change the Python code, he can use [`.hexdigest()`](https://docs.python.org/2/library/hashlib.html#hashlib.hash.hexdigest) and not do base64 encoding. – Reid Jan 21 '15 at 16:56
  • Thanks, noticed the sentence only after posting the answer. – Artjom B. Jan 21 '15 at 16:59
  • Thank you for your answers! That helped me a lot! Now I have to figure out if I will patch my database or change the python code.What would you recommend? – mr_5p4rk_ Jan 21 '15 at 17:06
  • @gimlithedwarf This is hard to answer. There are too many possibilities. If you are pressed for space, you can convert it to Base64 and save ~33% space in this column. If you ever send this as a URL parameter, you should either keep it in hex or convert it to the URL-safe version of Base64 (table 2 in RFC 4648). – Artjom B. Jan 21 '15 at 17:24