我有一个用python编写的代码
from base64 import b32encode, b32decode
somename = 'Karthik Bhat K'
b32encoded = b32encode(somename)
b32decoded = b32decode(b32encoded)
我想在php中编写b32encode和b32decode代码,因为python生成的密钥是由php编写的应用程序使用的。
Php确实有base64_encode
但是对于base32_encode,我没有找到任何builtins
答案 0 :(得分:0)
我目前正在使用自定义书写功能
// Note this functions can be improved!
function base32_encode($d): string{
// position mapping of characters
list($t, $b, $r) = array("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", "", "");
foreach(str_split($d) as $c) {
// Get 8 bits for each character
$b = $b . sprintf("%08b", ord($c));
}
// Since there are only 32 element in b32encode i.e A-Z and 2-7
// split the binary with 5 bits in each chunk
// since 2 ^ 5 is 32, gives items between 0 and 31
foreach(str_split($b, 5) as $c) {
// If any group has less than 5 bits fill it with 0 from the right
if (strlen($c) < 5)
$c = str_pad($c, 5, "0", STR_PAD_RIGHT);
// bindec converts binary to decimal
// The decimal is index in the array $t
// Get the value from the index of array $t
$r = $r . $t[bindec($c)];
}
return($r);
}
function base32_decode($d): string{
list($t, $b, $r) = array("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", "", "");
// Encode just split bit string into set of 5 character each
// This is the reverse of it. Find index in $t and convert it into
// 5 bit string and join each of them
foreach(str_split($d) as $c)
$b = $b . sprintf("%05b", strpos($t, $c));
// Each 8 bit of the string $b will give you the decoded string
foreach(str_split($b, 8) as $c) {
if (bindec($c)) { // Ignores the padding given in base32_encode
$r = $r . chr(bindec($c));
}
}
return($r);
}