简体   繁体   中英

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. What I can recreate from my data now is:


Content of 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:

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


What I did all the time in shell and need to do now in PHP is the following:

Again, same content of 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)? I tried pack / unpack / bin2hex /... and can't get the same result.

I'm trying to get a string with this content: "5293d47410d6f8ba46a7dc976e56cde7ef763798f259b3971a0b400cdf741d97"

from a starting point of base64_decode("uvjWEHTUk1LnzVZul9ynRpezWfKYN3bvlx103wxACxo=") . Any ideas?

If x8 is what you really need, which is 8 bytes, then the implementation would be as simple as

<?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.

Ideone: https://ideone.com/hBanqi

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