简体   繁体   中英

Python vs Javascript MD5 different for big numbers

I have the following code in Python:

port_name = 'test-PR-2092'
print int(hashlib.md5(port_name).hexdigest(), 16) % 10000
// 353

In Javascript, I am using the crypto library to try to do the same thing (I do not have control over the python code so I need to keep that the same):

parseInt(
  crypto
    .createHash('md5')
    .update('test-PR-2092')
    .digest('hex'),
  16
) % 10000
// 4160

Javascript yields a much different result.

Looking at the int's, they are very similar except that Javascript is in scientific notation.

Python: 158458604564589336383831436621974090353
Javascript: 1.5845860456458934e+38

Does anyone know where this discrepancy comes from?

Edit: Solved my own problem, and not a duplicate because no one has recommended BigInteger in any question I have seen

Here is the solution I found, BigInteger can take a hex value directly instead of first converting to an int.

const portHash = BigInteger(
    crypto
      .createHash('md5')
      .update('test-PR-2092')
      .digest('hex'),
    16
  )
    .mod(10000)
    .valueOf();
// 353

The answer is now the same as python.

Here is the library: https://www.npmjs.com/package/big-integer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM