Domanda

I'm trying to rewrite some javacode in a python script. One part of that is to deduce a simple number from a sha256 hash.

in java this function is called:

public static Long getId(byte[] publicKey) {
    byte[] publicKeyHash = Crypto.sha256().digest(publicKey);
    BigInteger bigInteger = new BigInteger(1, new byte[] {publicKeyHash[7], publicKeyHash[6], publicKeyHash[5],
            publicKeyHash[4], publicKeyHash[3], publicKeyHash[2], publicKeyHash[1], publicKeyHash[0]});
    return bigInteger.longValue();
}

The publicKey is binairy so I can't print it here, but the publicKeyHash I use for testing is: d9d5c57971eefb085e3abaf7a5a4a6cdb8185f30105583cdb09ad8f61886ec65

To my understandin the third line of this Java code converts d9d5c579 a number. The number that belongs to the hash above is 4273301882745002507

Now I'm looking for a piece / line of python code to generate that same number from that hash.

def getId(publicKey):
 publicKeyHash = binascii.hexlify(publicKey)
 p = publicKeyHash
 return(struct.unpack("Q",struct.pack("cccccccc",p[7],p[6],p[5],p[4],p[3],p[2],p[1],p[0]))[0])

Was a first attempt however this clearly doesn't work, it does return a number but not the correct one. Is there anyone here familiar with both languages and able to help my translate this function?

È stato utile?

Soluzione

How about (untested):

import hashlib
publicKeyHash = hashlib.sha256.digest(publicKey)
bigInt = 0
for byte in publicKeyHash[:7]:
  bigInt <<= 8
  bigInt |= byte

This worked:

from hashlib import sha256
import json
import struct
import binascii

def getId(publicKey):
 publicKeyHash = sha256(publicKey)
 p = publicKeyHash.digest()
 b = bytearray(p[:8])
 b.reverse()
 bigInt = 0
 for byte in b:
  bigInt <<= 8
  bigInt |= byte  
  #print bigInt
 return(bigInt)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top