C# 在PHP中将字节数组转换为字符串
作为PHP新手,我需要将字节数组转换为PHP函数中可能使用的字符串<代码>哈希_hmac(“sha256”,$payload,$key,true)C# 在PHP中将字节数组转换为字符串,c#,php,arrays,C#,Php,Arrays,作为PHP新手,我需要将字节数组转换为PHP函数中可能使用的字符串哈希_hmac(“sha256”,$payload,$key,true) $key将源自一个Guid,比如说{6fccde28-de32-4c0d-a642-7f0c601d1776},该Guid被转换为一个字节数组。由于hash_hmac对数据和密钥都采用字符串,因此我需要转换此字节数组,而不会由于不可打印的字符而丢失 我正在使用以下PHP代码: function guidToBytes($guid) { $guid_b
$key
将源自一个Guid,比如说{6fccde28-de32-4c0d-a642-7f0c601d1776}
,该Guid被转换为一个字节数组。由于hash_hmac对数据和密钥都采用字符串,因此我需要转换此字节数组,而不会由于不可打印的字符而丢失
我正在使用以下PHP代码:
function guidToBytes($guid) {
$guid_byte_order = [3,2,1,0,5,4,6,7,8,9,10,11,12,13,14,15];
$guid = preg_replace("/[^a-zA-Z0-9]+/", "", $guid);
$result = [];
for($i=0;$i<16;$i++)
$result[] = hexdec(substr($guid, 2 * $guid_byte_order[$i], 2));
return $result;
}
$payload = utf8_encode("Some data string");
$keyBytes = guidToBytes("6fccde28-de32-4c0d-a642-7f0c601d1776");
$key = implode(array_map("chr", $keyBytes));
$hash = hash_hmac("sha256", $payload, $key, true);
$result = base64_encode($hash);
在$key
中替换值将产生两种语言相同的base64
输出,留下$key
是错误的/不同的
所以,;如何将
$keyBytes
转换为$key
,而不丢失数据?您可以在PHP中使用chr函数
chr在输入中接收一个int并返回一个correspondent ascii字符
$strings = array_map("chr", $bytes);
$string = implode(" ", $strings);
希望我能有所帮助请尝试使用此函数将GUID转换为二进制字符串:
function guidToBytes($guid) {
$guid_byte_order = [3, 2, 1, 0, 5, 4, 7, 6, 8, 9, 10, 11, 12, 13, 14, 15];
$guid = preg_replace("/[^a-zA-Z0-9]+/", "", $guid);
$result = [];
foreach ($guid_byte_order as $offset) {
$result[] = hexdec(substr($guid, 2 * $offset, 2));
}
return $result;
}
我已经这样做了,但是数组映射不会“只是”生成另一个数组吗?结果还必须放在一个字符串中吗?您可以使用内爆函数获得一个字符串作为结果$strings=数组映射(“chr”,$bytes)$字符串=内爆(“,$strings);
function guidToBytes($guid) {
$guid_byte_order = [3, 2, 1, 0, 5, 4, 7, 6, 8, 9, 10, 11, 12, 13, 14, 15];
$guid = preg_replace("/[^a-zA-Z0-9]+/", "", $guid);
$result = [];
foreach ($guid_byte_order as $offset) {
$result[] = hexdec(substr($guid, 2 * $offset, 2));
}
return $result;
}