-1

我试图通过我创建的自定义函数加密数据......(基于base64)代码有效,但在一定程度上......它给出了随机结果(有时有效,有时无效)。

<?php
set_time_limit(0);
class encryptor{
 function encrypt($data){
  $all = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!?@,.&*()$; ";
  $chars = str_split($all, 1); // Split $all to array of single characters
  $text_chars = str_split($data, 1); // Split $data to array of single characters

  // Create array of unique results based on the characters from $all
  foreach($chars as $char){
   $array[$char] = md5(uniqid(rand(), true));
  }
  // Replace the input text with the results from $array 
  foreach($text_chars as $text_char){
   $data = str_replace($text_char,$array[$text_char], $data);
  }
  // Encode and compress $array as $solution
  $solution = gzcompress(base64_encode(json_encode($array)),9);
  // Return the encoded solution + Breaker + encoded and compressed input text
  return $solution."BREAKHERE".gzcompress(base64_encode($data),9);
 }
 function decrypt($data){
  // Break the encrypted code to two parts
  $exploded = explode('BREAKHERE', $data);
  // Decoding the contents
  $contents = base64_decode(gzuncompress($exploded[1]));
  // Decoding solution ($array)
  $solves = json_decode(base64_decode(gzuncompress($exploded[0])),true);
  $fliped = array_flip($solves);
  // Replace the encrypted data with the solution
  foreach($solves as $solve){
   $contents = str_replace($solve,$fliped[$solve], $contents);
  }
  return($contents); // Return decoded data
  }
 }

$text = "11 1";
$enc = new encryptor();
$encrypted = $enc->encrypt($text);
$decrypted = $enc->decrypt($encrypted);
echo $decrypted;
?>
4

1 回答 1

1

由于它只是为了好玩,因此此更改似乎使它起作用:

// Replace the input text with the results from $array
$encrypted = '';
foreach($text_chars as $text_char){
    //$data = str_replace($text_char,$array[$text_char], $data);
     $encrypted .= $array[$text_char];
}

在循环中运行str_replace会导致替换先前已替换的数据。

除此之外,为了使加密数据的传输更容易,我会改变:

return $solution."BREAKHERE".gzcompress(base64_encode($data),9);

至:

return base64_encode($solution."BREAKHERE".gzcompress($data,9);

然后在解密器中进行适当的更改。压缩数据可以包含空字符和不可打印字符,因此如果您对整个结果进行 base64 编码,则可以更轻松地传递它。

于 2012-09-19T18:22:33.197 回答