0

使用 PHP,我正在尝试将一个数字编码为另一个数字,我可以将其解码回原始数字。编码的字符串只能是数字,不应包含其他任何内容。

例如:10 变成 573563547892 或类似的东西。

我怎样才能在 PHP 中做这样的事情?我尝试了很多加密解密功能,但没有一个只输出数字。

我在一个不容易猜到的 URL 中寻找要使用的东西。

所以:http://www.me.com/index.PHP?page=20变成http://www.me.com/index.PHP?page=5705254782562466

4

2 回答 2

3

为什么不对原始数字使用数学运算?喜欢x变成x * y + z. 您只需进行反向操作即可获得原始号码。y考虑为和/或使用足够大的素数z

于 2013-09-23T18:07:22.723 回答
2

相当繁重,但非常好的加密,通过使用ord&chr一点。虽然这可行,但请考虑其他选项:仅能够使用字符串而不是数字已经使它变得更简单(base64_encode等等):

<?php
class Crypter {
  private $key = '';
  private $iv = '';
  function __construct($key,$iv){
    $this->key = $key;
    $this->iv  = $iv;
  }
  protected function getCipher(){
     $cipher = mcrypt_module_open(MCRYPT_BLOWFISH,'','cbc','');
     mcrypt_generic_init($cipher, $this->key, $this->iv);
     return $cipher;
  }
  function encrypt($string){
     $binary = mcrypt_generic($this->getCipher(),$string);
     $string = '';
     for($i = 0; $i < strlen($binary); $i++){
        $string .=  str_pad(ord($binary[$i]),3,'0',STR_PAD_LEFT);
     }
     return $string;
  }
  function decrypt($encrypted){
     //check for missing leading 0's
     $encrypted = str_pad($encrypted, ceil(strlen($encrypted) / 3) * 3,'0', STR_PAD_LEFT);
     $binary = '';
     $values = str_split($encrypted,3);
     foreach($values as $chr){
        $chr = ltrim($chr,'0');
        $binary .= chr($chr);
     }
     return mdecrypt_generic($this->getCipher(),$binary);
  }
}

$crypt = new Crypter('secret key','12348765');
$encrypted = $crypt->encrypt(1234);
echo $encrypted.PHP_EOL;
//fake missing leading 0
$encrypted = ltrim($encrypted,'0');
echo $encrypted.PHP_EOL;
$decrypted = $crypt->decrypt($encrypted);
echo $decrypted.PHP_EOL;

结果:

057044206104214236155088
57044206104214236155088
1234
于 2013-09-23T18:34:53.260 回答