Php change a number into another number that can be changed back to the original

后端 未结 2 828
孤街浪徒
孤街浪徒 2021-01-26 08:04

Using PHP, I\'m trying to encode a number into another number that I can decode back to the original number. The encoded string needs to be only numbers and should not contain a

相关标签:
2条回答
  • 2021-01-26 08:39

    Why not using a mathematicat operation on the original number? like x becomes x * y + z. you would only have to make the reverse operation to get the original number. consider using large enough prime numbers for y and/or z

    0 讨论(0)
  • 2021-01-26 08:48

    Quite heavy, but very good encryption, by using ord & chr a bit. While this works, consider other options: just being able to use strings rather then numbers already makes it a lot simpler (base64_encode etc.):

    <?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;
    

    Result:

    057044206104214236155088
    57044206104214236155088
    1234
    
    0 讨论(0)
提交回复
热议问题