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.

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

报告相同问题?

悬赏问题

  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因