PHP实现的DES加密解密实例代码

PHP实现的DES加密解密实例。分享给大家供大家参考,具体如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?php
$key = 'very important data';
function jiami($key, $str)
{
  /* Open module, and create IV */
  $td = mcrypt_module_open('des', '', 'ecb', '');
  //$td = mcrypt_module_open(MCRYPT_DES, '', MCRYPT_MODE_CBC, '');
  //$td = mcrypt_module_open('des', '', 'cbc', '');
  $key = substr($key, 0, mcrypt_enc_get_key_size($td));
  $iv_size = mcrypt_enc_get_iv_size($td);
  $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
  /* Initialize encryption handle */
  if (mcrypt_generic_init($td, $key, $iv) === -1)
  {
    return FALSE;
  }
  /* Encrypt data */
  $c_t = mcrypt_generic($td, $str);
  /* Clean up */
  mcrypt_generic_deinit($td);
  mcrypt_module_close($td);
  return $c_t;
}
function jiemi($key, $str)
{
  /* Open module, and create IV */
  $td = mcrypt_module_open('des', '', 'ecb', '');
  //$td = mcrypt_module_open(MCRYPT_DES, '', MCRYPT_MODE_CBC, '');
  //$td = mcrypt_module_open('des', '', 'cbc', '');
  $key = substr($key, 0, mcrypt_enc_get_key_size($td));
  $iv_size = mcrypt_enc_get_iv_size($td);
  $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
  /* Initialize encryption handle */
  if (mcrypt_generic_init($td, $key, $iv) === -1)
  {
    return FALSE;
  }
  /* Reinitialize buffers for decryption */
  $p_t = mdecrypt_generic($td, $str);
  /* Clean up */
  mcrypt_generic_deinit($td);
  mcrypt_module_close($td);
  return trim($p_t);
}
$str = 'hello world!';
echo 'key:' . $key . '<br>';
echo 'str:' . $str . '<br>';
$jiami = jiami($key, $str);
echo '加密:' . $jiami . '<br>';
file_put_contents('jiamiqian.txt', $str);
file_put_contents('jiamihou.txt', $jiami);
$jiemi = jiemi($key, $jiami);
echo '解密:' . $jiemi . '<br>';
© 版权声明
THE END
喜欢就支持一下吧
点赞14 分享
评论 抢沙发

请登录后发表评论