Cipher.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. /**
  3. * Cipher
  4. *
  5. * Provides encryption/decription functionality including URL shortening . By
  6. * default the encrypt/decrypt functions use AES to encrypt a string using
  7. * Cipher-block chaining (CBC) and then sign it using HMAC-SHA256 to prevent
  8. * initialization vector (IV) man-in-the-middle attacks against the first block .
  9. *
  10. * @package MicroMVC
  11. * @author David Pennington
  12. * @copyright (c) 2011 MicroMVC Framework
  13. * @license http://micromvc.com/license
  14. ********************************** 80 Columns *********************************
  15. */
  16. namespace Micro;
  17. class Cipher
  18. {
  19. /**
  20. * Encrypt a string
  21. *
  22. * @param string $text to encrypt
  23. * @param string $key a cryptographically random string
  24. * @param int $algo the encryption algorithm
  25. * @param int $mode the block cipher mode
  26. * @return string
  27. */
  28. public static function encrypt($text, $key, $algo = MCRYPT_RIJNDAEL_256, $mode = MCRYPT_MODE_CBC)
  29. {
  30. // Create IV for encryption
  31. $iv = mcrypt_create_iv(mcrypt_get_iv_size($algo, $mode), MCRYPT_RAND);
  32. // Encrypt text and append IV so it can be decrypted later
  33. $text = mcrypt_encrypt($algo, hash('sha256', $key, TRUE), $text, $mode, $iv) . $iv;
  34. // Prefix text with HMAC so that IV cannot be changed
  35. return hash('sha256', $key . $text) . $text;
  36. }
  37. /**
  38. * Decrypt an encrypted string
  39. *
  40. * @param string $text to encrypt
  41. * @param string $key a cryptographically random string
  42. * @param int $algo the encryption algorithm
  43. * @param int $mode the block cipher mode
  44. * @return string
  45. */
  46. public static function decrypt($text, $key, $algo = MCRYPT_RIJNDAEL_256, $mode = MCRYPT_MODE_CBC)
  47. {
  48. $hash = substr($text, 0, 64);
  49. $text = substr($text, 64);
  50. // Invalid HMAC?
  51. if(hash('sha256', $key . $text) != $hash) return;
  52. // Get IV off end of encrypted string
  53. $iv = substr($text, -mcrypt_get_iv_size($algo, $mode));
  54. // Decrypt string using IV and remove trailing \x0 padding added by mcrypt
  55. return rtrim(mcrypt_decrypt($algo, hash('sha256', $key, TRUE), substr($text, 0, -strlen($iv)), $mode, $iv), "\x0");
  56. }
  57. }
  58. // END