在Python中复制此Java哈希

在Python中复制此Java哈希,java,python,hash,byte,Java,Python,Hash,Byte,我试图在Python中复制此哈希代码,但这两种语言处理字节的方式不同,并生成非常不同的输出 有人能带我到这里吗 Java代码(原始代码) publicstaticstringhash(stringfilepath,stringsalt){ 字符串finalHash=null; Path Path=Path.get(filePath); 试一试{ MessageDigest md=MessageDigest.getInstance(“SHA-1”); 字节[]数据=文件。readAllBytes(

我试图在Python中复制此哈希代码,但这两种语言处理字节的方式不同,并生成非常不同的输出

有人能带我到这里吗

Java代码(原始代码)

publicstaticstringhash(stringfilepath,stringsalt){
字符串finalHash=null;
Path Path=Path.get(filePath);
试一试{
MessageDigest md=MessageDigest.getInstance(“SHA-1”);
字节[]数据=文件。readAllBytes(路径);
字节[]数据摘要=md.digest(数据);
byte[]hashDigest=md.digest(salt.getBytes(“ISO-8859-1”);
byte[]xorBytes=新字节[dataDigest.length];
对于(int i=0;i1);
}
finalHash=(新的HexBinaryAdapter()).marshal(xorBytes);
}捕获(IOException | NosuchAlgorithme异常){
e、 printStackTrace();
}
返回finalHash;
}
Python代码(由我翻译)

def生成散列(文件路径:str,salt:bytes)->str:
打开(文件路径“rb”)作为f:
data=f.read()
hashed_file=sha1(data).digest()
hashed_salt=sha1(salt).digest()
xor_字节=[]
对于范围内的i(len(散列文件)):
xor_bytes.append((散列_文件[i]>1))
返回“”。join(映射(chr,xor_字节))#这可能与HexBinaryAdapter不同

存在以下问题:

  • 在Python代码中错误地实现了shift操作:

    在Python代码中,生成的散列存储在类似字节的对象中,作为
    0
    255
    之间的无符号整数值列表,例如
    0xc8=11001000=200
    。在Java中,整数被存储为有符号值,因此二者的补码被用来表示负数。如果值
    0x8c
    存储在
    字节
    变量中,则该值将被解释为
    -56

    >
    -运算符在二进制级别为有符号值和无符号值生成不同的结果,因为它是一个保留符号的算术移位运算符。例如:

    signed       -56 >> 1 = 1110 0100 = -28
    unsigned     200 >> 1 = 0110 0100 = 100
    

    我现在正在比较数据,并注意到java与python中字节的问题。现在提供更正后,代码返回相同的输出。非常感谢你!!
    
    signed       -56 << 1 = 1 1001 0000 = -112
    unsigned     200 << 1 = 1 1001 0000 = 400
    
    xor_bytes.append((hashed_file[i] << 1 ^ hashed_salt[i] >> 1))
    
    xor_bytes.append((hashed_file[i] << 1 ^ tc(hashed_salt[i]) >> 1) & 0xFF)
    
    def tc(val):
        if val > 127:
            val = val - 256
        return val
    
    bytes(xor_bytes).hex() 
    
    binascii.b2a_hex(bytes(xor_bytes))
    
    saltStr = 'MySalt'
    salt = saltStr.encode('ISO-8859-1')