PHP encrypt decrypt

Php code posted by Caiwangqin
created at 16 Dec 10:47, updated at 18 Jan 11:11

Edit | Back
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<?php
function getkeyiv($key_size, $iv_size, $key, $iv='') {
  if ($iv == '') {
    $iv = 'OpenSSL for Ruby rulez!';
  }

  $iv = substr($iv,0,$iv_size);
  
  $gen = '';
  do  {
    $gen = $gen.md5($gen.$key.$iv,true);
  } while (strlen($gen)<($iv_size+$key_size));

  $o[0] = substr($gen,0,$key_size);
  $o[1] = $iv; //this is not the generated IV,
                     //just the original "salt" cut to the required size
  return $o;
}

function trimpadding($str) {
   if (ord($str[strlen($str)-1]) < 9) {
    return rtrim($str,$str[strlen($str)-1]);
  } else {
    return $str;    
  }
} 

function encipher($data_to_encode){
  $key = 'secretkey';
    
    $td = mcrypt_module_open(MCRYPT_TRIPLEDES, '',  MCRYPT_MODE_CBC, '');

  $iv_size = mcrypt_enc_get_iv_size($td);
  $key_size = mcrypt_enc_get_key_size($td);

  $genkey = getkeyiv($key_size, $iv_size,$key);

  if (mcrypt_generic_init($td,$genkey[0],$genkey[1]) != -1) {
          $encoded_data = mcrypt_generic($td, $data_to_encode);
  }

  mcrypt_generic_deinit($td);
  mcrypt_module_close($td);

    return base64_encode($encoded_data);
}

function decipher($encoded) {
  $key = 'secretkey';
  $decrypted='';

  $enc = base64_decode($encoded);
  $td = mcrypt_module_open(MCRYPT_TRIPLEDES, '',  MCRYPT_MODE_CBC, '');

  $iv_size = mcrypt_enc_get_iv_size($td);
  $key_size = mcrypt_enc_get_key_size($td);

  $genkey = getkeyiv($key_size, $iv_size,$key);

  if (mcrypt_generic_init($td,$genkey[0],$genkey[1]) != -1) {
          $decrypted = mdecrypt_generic($td, $enc);
  }

  mcrypt_generic_deinit($td);
  mcrypt_module_close($td);

  return trimpadding($decrypted);
}
?>
1.61 KB in 8 ms with coderay