简体   繁体   English

PHP编码问题:如何将base64编码的uint8字节编码为十六进制

[英]PHP encoding problem: how to encode base64 encoded uint8 bytes to hex

My problem is that I was some time ago base64 encoding random bytes from openssl sha256 in C (as uint8_t), feeding them into a shell script and using the output. My problem is that I was some time ago base64 encoding random bytes from openssl sha256 in C (as uint8_t), feeding them into a shell script and using the output. What I can recreate from my data now is:我现在可以从我的数据中重新创建的是:


Content of file.txt: uvjWEHTUk1LnzVZul9ynRpezWfKYN3bvlx103wxACxo file.txt 的内容: uvjWEHTUk1LnzVZul9ynRpezWfKYN3bvlx103wxACxo

test@test:~# base64 -d file.txt | od -t x1 0000000 ba f8 d6 10 74 d4 93 52 e7 cd 56 6e 97 dc a7 46 0000020 97 b3 59 f2 98 37 76 ef 97 1d 74 df 0c 40 0b 1a

The output is the same as calling in PHP: output 与 PHP 中调用相同:

echo bin2hex(base64_decode("uvjWEHTUk1LnzVZul9ynRpezWfKYN3bvlx103wxACxo=")); baf8d61074d49352e7cd566e97dca74697b359f2983776ef971d74df0c400b1a baf8d61074d49352e7cd566e97dca74697b359f2983776ef971d74df0c400b1a


What I did all the time in shell and need to do now in PHP is the following:我在 shell 中一直在做的,现在在 PHP 中需要做的事情如下:

Again, same content of file.txt: uvjWEHTUk1LnzVZul9ynRpezWfKYN3bvlx103wxACxo同样,file.txt 的内容相同: uvjWEHTUk1LnzVZul9ynRpezWfKYN3bvlx103wxACxo

test@test:~# base64 -d file.txt | od -t x8 0000000 5293d47410d6f8ba 46a7dc976e56cde7 0000020 ef763798f259b397 1a0b400cdf741d97

My problem here: what is now the equal procedure in PHP (to od -t x8 in shell)?我的问题是:现在 PHP 中的平等程序是什么(在 shell 中为 od -t x8 )? I tried pack / unpack / bin2hex /... and can't get the same result.我试过 pack / unpack / bin2hex /... 并不能得到相同的结果。

I'm trying to get a string with this content: "5293d47410d6f8ba46a7dc976e56cde7ef763798f259b3971a0b400cdf741d97"我正在尝试获取包含以下内容的字符串:“5293d47410d6f8ba46a7dc976e56cde7ef763798f259b3971a0b400cdf741d97”

from a starting point of base64_decode("uvjWEHTUk1LnzVZul9ynRpezWfKYN3bvlx103wxACxo=") .base64_decode("uvjWEHTUk1LnzVZul9ynRpezWfKYN3bvlx103wxACxo=")的起点开始。 Any ideas?有任何想法吗?

If x8 is what you really need, which is 8 bytes, then the implementation would be as simple as如果x8是您真正需要的,即 8 个字节,那么实现将非常简单

<?php

$str = 'uvjWEHTUk1LnzVZul9ynRpezWfKYN3bvlx103wxACxo';
$bin = base64_decode($str);

if (strlen($bin) % 8 !== 0) {
    throw new \RuntimeException('data length should be divisible by 8');
}

$result = '';

for ($i = 0; $i < strlen($bin); $i += 8) {
    for ($j = $i + 7; $j >= $i; --$j) {
        $result .= bin2hex($bin[$j]);
    }
}

echo $result;

It iterates over blocks of 8 bytes, then dumps them in reverse order each.它遍历 8 个字节的块,然后以相反的顺序转储它们。

Ideone: https://ideone.com/hBanqi ideone: https://ideone.com/hBanqi

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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