我正在尝试构建一个生成加密密钥的应用程序,然后将其直接放在C 应用程序的代码中以解密它。
我对PHP中的字符串如何转换为C 中使用的格式感到困惑。
举例来说,请在此处查看此问题:XTEA在PHP中加密和C
中的解密dschulz的答案如何获取字符串
annoying monkey
to
uint32_t key[4] = {0x6f6e6e61, 0x676e6979, 0x6e6f6d20, 0x0079656b };
以及如何在PHP中完成,因此它以该格式打印该行?
我尝试将字符串转换为十六进制并固定0x,但它不起作用,任何帮助都将不胜感激。
仅仅是hex&小末日格式:
a n n o y i n g m o n k e y
Hex: 61 6e 6e 6f 79 69 6e 67 20 6d 6f 6e 6b 65 79 00
/ / / /
reverse reverse reverse reverse
/ / / /
{0x6f6e6e61, 0x676e6979, 0x6e6f6d20, 0x0079656b };
使用以下来转换字符串:
<?php
$var = "annoying monkey";
$hex = '';
for ($i=0; $i<strlen($var); $i++){
$ord = ord($var[$i]);
$hexCode = dechex($ord);
$hex .= substr('0'.$hexCode, -2);
}
echo $hex; // 616e6e6f79696e67206d6f6e6b6579
之后,您只需要将字符串分成8个,然后逆转2位数字的组(4个字母中的每个(
$parts = str_split($hex,8);
foreach($parts as $key=>$value){
// pad right to make last group 8 chars long, even if it's shorter
$parts[$key] = str_pad($value, 8, "0", STR_PAD_RIGHT);
// split it into groups of 2 digits - each letter
$innerParts = str_split($parts[$key],2);
// reverse the order
$innerParts = array_reverse($innerParts);
// join and start with '0x'
$parts[$key] = "0x".implode('',$innerParts);
}
print_r($parts);
//Array
//(
// [0] => 0x6f6e6e61
// [1] => 0x676e6979
// [2] => 0x6e6f6d20
// [3] => 0x0079656b
//)
您可以在这里看到它:
https://3v4l.org/avobb
要获得最终字符串,
$string = 'uint32_t key['.count($parts).'] = {'. implode(',', $parts). '};';
echo $string;
// uint32_t key[4] = {0x6f6e6e61,0x676e6979,0x6e6f6d20,0x0079656b};
trick派,鉴于在您的原始PHP字符串中,它们都是"大端订单和大端字节订单",这是转换它们的一种方法(此方法使用更多的方法CPU超过要求的,肯定有一种比这更快的方法(
<?php
// the raw key binary, big endian bit order, big endian byte order:
$key_bit_order_big_byte_order_big = "annoying_monkey";
//<pad>
// pad it to 32bits/4 bytes (uint32_t)
$pad_bytes = strlen($key_bit_order_big_byte_order_big) % 4;
if($pad_bytes > 0){
$pad_bytes = 4 - $pad_bytes;
assert($pad_bytes > 0);
$key_bit_order_big_byte_order_big .= str_repeat("x00", $pad_bytes);
}
//</pad>
// convert from "big endian bit order, big endian byte order" to
// "little endian bit order, big endian byte order":
$key_bit_order_little_byte_order_big = strrev($key_bit_order_big_byte_order_big);
// convert from "little endian bit order, big endian byte order" to
// "little endian bit order, little endian byte order":
$key_bit_order_little_byte_order_little = implode("", array_reverse(str_split($key_bit_order_little_byte_order_big, 4), false));
// now to c++-ify it:
$key_chunks_little_endian = str_split($key_bit_order_little_byte_order_little, 4);
foreach($key_chunks_little_endian as &$chunk){
$chunk = "0x".bin2hex($chunk);
}
unset($chunk);
echo "uint32_t key[".count($key_chunks_little_endian)."] = {".implode(", ", $key_chunks_little_endian)."};";
输出:
uint32_t key[4] = {0x6f6e6e61, 0x676e6979, 0x6e6f6d5f, 0x0079656b};