dongshang5862 2014-06-21 15:10 采纳率: 0%
浏览 73
已采纳

PHP简单的字符串加密和解密

Is there a simple function in PHP other than mcrypt() that can encrypt and decrypt a string.

I was trying out the code below, but that's too much for what I'm trying to do.

I'm trying to encrypt page numbers that are sent with a URL, so users will not be able to access a page simply by making changes to the page number in the browsers location bar. My page number has some other data too, that I do not want visible to users.

Example: http://www.example.com/p10:05 to http://www.example.com/895f852d22d558esc23

I don't need such high level encryption and decryption like in the code below. Just something that can do like in my example is sufficient.

Another reason I do not like using mcrypt, is because of the 2 == it adds to the end of a string.

$salt ='iodine';

    function simple_encrypt($text)
    {
        global $salt;
        return trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $salt, $text, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND))));
    }

    function simple_decrypt($text)
    {
        global $salt;
        return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $salt, base64_decode($text), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND)));
    }

    echo simple_encrypt('Hello')
  • 写回答

1条回答 默认 最新

  • douguai7291 2014-06-21 15:48
    关注

    MCrypt does not add those == characters to the string, the base 64 encoding does. It is possible to simply remove them. Just make sure that the base64 string is a multiple of 4 characters by adding them back again when the string is received.

    Base 64 can contain the '/' and '+' characters by default (depending on the input). Replace them with URL safe - and _ characters.

    The code shows MCRYPT_RIJNDAEL_256 which is not AES; it is Rijndael with a 256 bit block size. Using MCRYPT_RIJNDAEL_128 - which is AES - would be better. This still allows the code to encrypt up to 16 character number values and it will decrease the output size.

    There is no need to generate an IV if ECB mode is used, so remove that part of the method. There is no need to add unnecessary work for the system random number generator.

    The $salt value is actually the key value, better name it as such to avoid confusion.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试