PHP中crc32b的输出不等于Python

2024-09-28 19:34:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将PHP代码片段转换为Python3代码,但是print和{}的输出是不同的。在

你可以在第一步看到。在

你知道问题出在哪里吗?我也附加了输入数组,但我认为它们是相等的。在

�W2+ vs ee7523b2

编辑

当我将raw从TRUE切换到FALSE时,第一步的输出是相同的。$d = strrev(hash("crc32b", $d, FALSE)) . $d

但问题是我必须把PHP转换成Python,而不是相反,因为在第2步中我需要有相同的输出。在

PHP输出(CMD)

^{pr2}$

PYTHON输出

^{3}$

PHP

<?php
$suma = "100";
$datum = "20190101";
$varsym = "11111111";
$konsym = "";
$specsym = "";
$poznamka = "Faktúra";
$iban = "SK6807200002891987426353";
$swift = "";

$d = implode("\t", array(
    0 => '',
    1 => '1',
    2 => implode("\t", array(
        true,
        $suma,                      // SUMA
        'EUR',                      // JEDNOTKA
        $datum,                 // DATUM
        $varsym,                    // VARIABILNY SYMBOL
        $konsym,                        // KONSTANTNY SYMBOL
        $specsym,                       // SPECIFICKY SYMBOL
        '',
        $poznamka,                  // POZNAMKA
        '1',
        $iban,  // IBAN
        $swift,                 // SWIFT
        '0',
        '0'
    ))
));
// 0
echo "0 -> ".$d."\n";
$d = strrev(hash("crc32b", $d, TRUE)) . $d;
// 1
echo "1 -> ".$d."\n";
$x = proc_open("/usr/bin/xz '--format=raw' '--lzma1=lc=3,lp=0,pb=2,dict=128KiB' '-c' '-'", [0 => ["pipe", "r"], 1 => ["pipe", "w"]], $p);
fwrite($p[0], $d);
fclose($p[0]);
$o = stream_get_contents($p[1]);
fclose($p[1]);
proc_close($x);

$d = bin2hex("\x00\x00" . pack("v", strlen($d)) . $o);
// 2
echo "2 -> ".$d."\n";
?>

PYTHON

    def crc32b(x):
        h = zlib.crc32(x)
        x='%08X' % (h & 0xffffffff,)
        return x.lower()

    t = "\t"
    gen = t.join(["1",
                  "100", # SAME VARIABLES 
                  "EUR",
                  "20190101",
                  "11111111",
                  "",
                  "",
                  "",
                  "Faktúra",
                  "1",
                  "SK6807200002891987426353",
                  "",
                  "0",
                  "0"]
                 )

    d = t.join([
        "", "1", gen])
    # 0
    print(f"0 -> {d}")
    hashD = crc32b(d.encode()) # OK

    hashD = hashD[::-1]
    # hashD = str(binascii.unhexlify(hashD))
    d = hashD + d
    # 1
    print(f"1 -> {d}")
    args = shlex.split("xz '--format=raw' '--lzma1=lc=3,lp=0,pb=2,dict=128KiB' -c -")
    process = subprocess.Popen(args, shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE)
    output = process.communicate(d.encode())

    pack = "\x00\x00" + str(struct.pack("H", len(d))) + str(output[0])

    d = binascii.hexlify(pack.encode())
    # 2
    print(f"2 -> {d}")

Tags: 代码echotruerawsymbolpackencodephp
2条回答

无法与PHP一起工作。
根据[Python 3]: zlib.crc32(data[, value])强调是我的):

Computes a CRC (Cyclic Redundancy Check) checksum of data. The result is an unsigned 32-bit integer.

你在混淆:

  • 它的值-也可以看作长度为4的ASCII字符串
  • 其值的文本表示形式(inbase16),它是一个长度为8的字符串
>>> crc = 0x2B3257EE  # The value returned by zlib.crc32 for your text
>>> type(crc), crc
(<class 'int'>, 724719598)
>>>
>>> [chr((crc >> shift_bits) & 0xFF) for shift_bits in [0, 8, 16, 24]]
['î', 'W', '2', '+']

注意事项

  • 一种方法是将数字的4个字节转换成字符
  • 要从uint32值中获取一个字节,必须将uint32按值([3,2,1,0])乘以8字节的顺序向右移动([Python.Wiki]: BitwiseOperators
    • 另外,为了去除不需要的字节(除最右边的字节以外的任何字节),结果值也是ed,并使用0xFF255
  • 由于little endianness,字节按相反的顺序(从右到左)转换为chars
  • 1stchar'î')看起来不同,但只是一个表示问题(在我的控制台vs您的控制台中)

将其集成到代码中,您需要修改crc32b函数(并删除对hashD的任何进一步处理)以:

def crc32b(x):
    crc = zlib.crc32(x)
    return "".join([chr((crc >> shift_bits) & 0xFF) for shift_bits in [0, 8, 16, 24]])

有关此一般主题的详细信息,请检查[SO]: Python struct.pack() behavior (@CristiFati's answer)。在

@EDIT0

添加从十六进制表示形式开始的版本:

>>> crc = 0x2B3257EE
>>> crc_hex = "{:08X}".format(crc)
>>> crc_hex
'2B3257EE'
>>>
>>> list(reversed([chr(int(crc_hex[2 * i] + crc_hex[2 * i + 1], 16)) for i in range(len(crc_hex) // 2)]))
['î', 'W', '2', '+']
  • 从我的PoV来看,这更难看,而且效率也很低(许多来回转换),但无论如何都要发布,因为有些人在位操作上有困难
  • 关键点是一次处理2hexchars,只有在转换后才能反转

您只需删除函数hash()的第三个参数

如果将此参数设置为true,hash将返回原始二进制数据,php将尝试将其解析为文本字符串,而您希望得到十六进制结果

相关问题 更多 >