我计划制作一个可以将文件编码为ASCII字符并解码为可读文本的类。基本上,我的编码思路是将所有非空格字符编码为ASCII,然后将空格替换为随机的非数字字符。
Example: "Hello World!" to "72101108108111^8711111410810033"
以这种方式,如果我有一个包含多个段落的整个文件并对其进行编码,那么将字符转换为ASCII并不是很明显。到目前为止,这是我的代码:
$text = str_split("Hello World!");
$content = "";
$random = str_split("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!@#$%^&*-+?/_=");
foreach($text as $t){
if ($t == " "){
$count = rand(1,66);
$content .= $random[$count-1];
}
else
$content .= ord($t);
}
echo $content."<br>";
$decode = str_split($content);
$script = "";
$tostring = "";
foreach($decode as $d){
if (is_numeric($d)){
$tostring .= $d;
}else{
$script .= chr($tostring);
$tostring = "";
}
}
echo $script;
我正在努力找出我的代码存在的问题。这是它的结果:
ASCII: 72101108108111-8711111410810033
TEXT: O
请赐教!
答案 0 :(得分:2)
两个问题:您试图将多个数字传递给旨在返回单个字符的chr()
,并且您无法知道数字将要持续多久。使用上面的示例:是72、101、108、108还是72、10、10、81、08?因此,使用sprintf()
将数字固定为3位数字,然后您将知道何时将数据传递到chr()
并继续进行解码。
$text = str_split("Hello World!");
$content = "";
$random = str_split("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!@#$%^&*-+?/_=");
foreach($text as $t){
if ($t === " "){
$count = rand(1, 66);
$content .= $random[$count - 1];
} else {
// this will always be three digits now
$content .= sprintf("%03d", ord($t));
}
}
echo $content."<br>";
$decode = str_split($content);
$script = "";
$tostring = "";
foreach($decode as $d){
if (is_numeric($d)){
$tostring .= $d;
if (strlen($tostring) === 3) {
// you've got 3 numbers so you can decode and reset
$script .= chr($tostring);
$tostring = "";
}
} else {
// also you weren't putting your spaces back in
$script .= " ";
}
}
echo $script;