Encrypting and Decrypting with Mcrypt


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. private $_key='some key';
  2.  
  3. /**
  4. * Encrypt using mcrypt
  5. *
  6. * Value is encrypted with mcrypt and base64
  7. *
  8. * @param mixed $val Can be string or int
  9. * @return string Encoded value
  10. */
  11.  
  12. function mcryptEncode($val) {
  13. $iv_size = mcrypt_get_iv_size(MCRYPT_XTEA, MCRYPT_MODE_ECB);
  14. $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
  15. $enc = mcrypt_encrypt(MCRYPT_XTEA, $this->_key, $val, MCRYPT_MODE_ECB, $iv);
  16. $benc = base64_encode($enc);
  17. return $benc;
  18. }
  19.  
  20. /**
  21. * Decrypt using mcrypt
  22. *
  23. * Takes value encrypted with mcrypt and base64 and decrypts
  24. *
  25. * @param string $benc Encrypted mcrypt and base64 value
  26. * @return string Decoded value
  27. */
  28.  
  29. function mcryptDecode($benc) {
  30. $bdec = base64_decode($benc);
  31. $iv_size = mcrypt_get_iv_size(MCRYPT_XTEA, MCRYPT_MODE_ECB);
  32. $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
  33. $dec = mcrypt_decrypt(MCRYPT_XTEA, $this->_key, $bdec, MCRYPT_MODE_ECB, $iv);
  34. return $dec;
  35. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.