欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

PHP使用DES进行加密和解密

程序员文章站 2024-02-14 18:41:22
...

php中有一个扩展可以支持DES的加密算法,是:extension=php_mcrypt.dll

在配置文件中将这个扩展打开还不能够在windows环境下使用

需要将PHP文件夹下的 libmcrypt.dll 拷贝到系统的 system32 目录下,这是通过phpinfo可以查看到mcrypt表示这个模块可以正常试用了。

下面是PHP中使用DES加密解密的一个例子:

  1. //$input - stuff to decrypt
  2. //$key - the secret key to use
  3. function do_mencrypt($input, $key)
  4. {
  5. $input = str_replace(""n", "", $input);
  6. $input = str_replace(""t", "", $input);
  7. $input = str_replace(""r", "", $input);
  8. $key = substr(md5($key), 0, 24);
  9. $td = mcrypt_module_open('tripledes', '', 'ecb', '');
  10. $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
  11. mcrypt_generic_init($td, $key, $iv);
  12. $encrypted_data = mcrypt_generic($td, $input);
  13. mcrypt_generic_deinit($td);
  14. mcrypt_module_close($td);
  15. return trim(chop(base64_encode($encrypted_data)));
  16. }
  17. //$input - stuff to decrypt
  18. //$key - the secret key to use
  19. function do_mdecrypt($input, $key)
  20. {
  21. $input = str_replace(""n", "", $input);
  22. $input = str_replace(""t", "", $input);
  23. $input = str_replace(""r", "", $input);
  24. $input = trim(chop(base64_decode($input)));
  25. $td = mcrypt_module_open('tripledes', '', 'ecb', '');
  26. $key = substr(md5($key), 0, 24);
  27. $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
  28. mcrypt_generic_init($td, $key, $iv);
  29. $decrypted_data = mdecrypt_generic($td, $input);
  30. mcrypt_generic_deinit($td);
  31. mcrypt_module_close($td);
  32. return trim(chop($decrypted_data));
  33. }
复制代码

PHP, DES