Reputation: 1
I'm trying to encrypt a string to send away to another app, and my Python and Nodejs implementation's outputs are not matching. Can someone tell me the difference between these two methods, or what I'm doing wrong? I have the Nodejs version working and compatible, and I'd like the may the Python version match its output.
NodeJS:
var jsSHA = require("jssha")
var hash = new jsSHA("SHA3-512","HEX");
hash.update("6b0d");
console.log(hash.getHash("B64"))
// $ 9G1hk/ztGnZyk1HGPQMYAtrkg6dFoPW+s5TZou101Yl4QJyaSe+l1uZIEpi/rosNCfpsKOI7kh5usLrn06uYtQ==
Python:
import hashlib
import base64
hash = hashlib.sha3_512("6b0d".encode()).digest()
print(base64.b64encode(hash).decode())
# $ mBg3+maf_9gyfkDIIsREJM8VjCxKEo3J5MrCiK8Bk6FFJZ81IcAc8PjTRB+/3jd0MGnynqjkSZEg++c40JRwhQ==
Can anyone tell the difference, or something I'm missing in Python?
Edit: Added output strings.
Node:
$ 9G1hk/ztGnZyk1HGPQMYAtrkg6dFoPW+s5TZou101Yl4QJyaSe+l1uZIEpi/rosNCfpsKOI7kh5usLrn06uYtQ==
Python:
$ mBg3+maf_9gyfkDIIsREJM8VjCxKEo3J5MrCiK8Bk6FFJZ81IcAc8PjTRB+/3jd0MGnynqjkSZEg++c40JRwhQ==
Upvotes: 0
Views: 351
Reputation: 155654
"6b0d".encode()
is not converting from str
hex representation to two raw bytes, it's converting to four raw bytes representing each of the characters (b'6b0d'
), and hashing that (str.encode()
is for encoding based on a character encoding, and it defaults to UTF-8; there's no convenient way to use it to convert to/from hex representation on Python 3). By contrast,
var hash = new jsSHA("SHA3-512","HEX");
is telling the library to interpret the input as a hex representation, so it decodes it from four characters to two bytes on your behalf and hashes that.
To make Python do the same thing, change:
"6b0d".encode()
to:
bytes.fromhex("6b0d")
which will get the same two bytes that jsSHA is producing for hashing on your behalf (equivalent to b'\x6b\x0d'
, or as Python would represent it when echoing, b'k\r'
, since both bytes have shorter printable representations in ASCII).
Note: On older versions of Python, you'd import binascii
and replace bytes.fromhex
with binascii.unhexlify
, but all supported versions provide it as an alternate constructor on the built-in bytes
type, so that's the easiest approach.
Upvotes: 2