PageRenderTime 44ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 0ms

/sgl/includes/qcubed/_core/framework/QCryptography.class.php

http://logisticsouth.googlecode.com/
PHP | 196 lines | 122 code | 31 blank | 43 comment | 25 complexity | fbc13cd6655d6e4e08c239044417199e MD5 | raw file
Possible License(s): LGPL-2.1, GPL-2.0
  1. <?php
  2. // Requires libmcrypt v2.4.x or higher
  3. class QCryptographyException extends QCallerException {}
  4. class QCryptography extends QBaseClass {
  5. protected $objMcryptModule;
  6. protected $blnBase64;
  7. protected $strKey;
  8. protected $strIv;
  9. /**
  10. * Default Base64 mode for any new QCryptography instances that get constructed.
  11. *
  12. * This is similar to MIME-based Base64 encoding/decoding, but is safe to use
  13. * in URLs, POST/GET data, and any other text-based stream.
  14. *
  15. * Note that by setting Base64 to true, it will result in an encrypted data string
  16. * that is 33% larger.
  17. * @var string Base64
  18. */
  19. public static $Base64 = true;
  20. /**
  21. * Default Key for any new QCryptography instances that get constructed
  22. * @var string Key
  23. */
  24. public static $Key = "qc0Do!d3F@lT.k3Y";
  25. /**
  26. * The Random Number Generator the library uses to generate the IV:
  27. * - MCRYPT_DEV_RANDOM = /dev/random (only on *nix systems)
  28. * - MCRYPT_DEV_URANDOM = /dev/urandom (only on *nix systems)
  29. * - MCRYPT_RAND = the internal PHP srand() mechanism
  30. * (on Windows, you *must* use MCRYPT_RAND, b/c /dev/random and /dev/urandom doesn't exist)
  31. *
  32. * TODO: there appears to be some /dev/random locking issues on the QCubed development
  33. * environment (using Fedora Core 3 with PHP 5.0.4 and LibMcrypt 2.5.7). Because of this,
  34. * we are using MCRYPT_RAND be default. Feel free to change to to /dev/*random at your own risk.
  35. */
  36. public function __construct($strKey = null, $blnBase64 = null, $strCipher = null, $strMode = null, $strRandomSource = null) {
  37. if (!function_exists('mcrypt_module_open')) {
  38. throw new QCryptographyException("PHP cryptography components (libmcrypt module) are not installed");
  39. }
  40. // Get the Key
  41. if (is_null($strKey)) {
  42. $strKey = self::$Key;
  43. }
  44. // Get the Base64 Flag
  45. try {
  46. if (is_null($blnBase64)) {
  47. $this->blnBase64 = QType::Cast(self::$Base64, QType::Boolean);
  48. } else {
  49. $this->blnBase64 = QType::Cast($blnBase64, QType::Boolean);
  50. }
  51. } catch (QCallerException $objExc) {
  52. $objExc->IncrementOffset();
  53. throw $objExc;
  54. }
  55. // Get the Cipher
  56. if (is_null($strCipher)) {
  57. $strCipher = MCRYPT_TRIPLEDES;
  58. }
  59. // Get the Mode
  60. if (is_null($strMode)) {
  61. $strMode = MCRYPT_MODE_ECB;
  62. }
  63. if (is_null($strRandomSource)) {
  64. $strRandomSource = MCRYPT_RAND;
  65. }
  66. $this->objMcryptModule = mcrypt_module_open($strCipher, null, $strMode, null);
  67. if (!$this->objMcryptModule) {
  68. throw new QCryptographyException('Unable to open LibMcrypt Module');
  69. }
  70. // Determine IV Size
  71. $intIvSize = mcrypt_enc_get_iv_size($this->objMcryptModule);
  72. // Create the IV
  73. if ($strRandomSource != MCRYPT_RAND) {
  74. // Ignore All Warnings
  75. set_error_handler('QcodoHandleError', 0);
  76. $intCurrentLevel = error_reporting();
  77. error_reporting(0);
  78. $strIv = mcrypt_create_iv($intIvSize, $strRandomSource);
  79. error_reporting($intCurrentLevel);
  80. restore_error_handler();
  81. // If the RandomNumGenerator didn't work, we revert back to using MCRYPT_RAND
  82. if (strlen($strIv) != $intIvSize) {
  83. srand();
  84. $strIv = mcrypt_create_iv($intIvSize, MCRYPT_RAND);
  85. }
  86. } else {
  87. srand();
  88. $strIv = mcrypt_create_iv($intIvSize, MCRYPT_RAND);
  89. }
  90. $this->strIv = $strIv;
  91. // Determine KeySize length
  92. $intKeySize = mcrypt_enc_get_key_size($this->objMcryptModule);
  93. // Create the Key Based on Key Passed In
  94. $this->strKey = substr(md5($strKey), 0, $intKeySize);
  95. }
  96. public function Encrypt($strData) {
  97. // Initialize Encryption
  98. $intReturnValue = mcrypt_generic_init($this->objMcryptModule, $this->strKey, $this->strIv);
  99. if (($intReturnValue === false) || ($intReturnValue < 0))
  100. throw new QCryptographyException('Incorrect Parameters used in LibMcrypt Initialization');
  101. // Add Length to strData
  102. $strData = strlen($strData) . '/' . $strData;
  103. $strEncryptedData = mcrypt_generic($this->objMcryptModule, $strData);
  104. if ($this->blnBase64) {
  105. $strEncryptedData = base64_encode($strEncryptedData);
  106. $strEncryptedData = str_replace('+', '-', $strEncryptedData);
  107. $strEncryptedData = str_replace('/', '_', $strEncryptedData);
  108. $strEncryptedData = str_replace('=', '', $strEncryptedData);
  109. }
  110. // Deinitialize Encryption
  111. if (!mcrypt_generic_deinit($this->objMcryptModule))
  112. throw new QCryptographyException('Unable to deinitialize encryption buffer');
  113. return $strEncryptedData;
  114. }
  115. public function Decrypt($strEncryptedData) {
  116. // Initialize Encryption
  117. $intReturnValue = mcrypt_generic_init($this->objMcryptModule, $this->strKey, $this->strIv);
  118. if (($intReturnValue === false) || ($intReturnValue < 0))
  119. throw new QCryptographyException('Incorrect Parameters used in LibMcrypt Initialization');
  120. if ($this->blnBase64) {
  121. $strEncryptedData = str_replace('_', '/', $strEncryptedData);
  122. $strEncryptedData = str_replace('-', '+', $strEncryptedData);
  123. $strEncryptedData = base64_decode($strEncryptedData);
  124. }
  125. $intBlockSize = mcrypt_enc_get_block_size($this->objMcryptModule);
  126. $strDecryptedData = mdecrypt_generic($this->objMcryptModule, $strEncryptedData);
  127. // Figure Out Length and Truncate
  128. $intPosition = strpos($strDecryptedData, '/');
  129. if (!$intPosition)
  130. throw new QCryptographyException('Invalid Length Header in Decrypted Data');
  131. $intLength = substr($strDecryptedData, 0, $intPosition);
  132. $strDecryptedData = substr($strDecryptedData, $intPosition + 1);
  133. $strDecryptedData = substr($strDecryptedData, 0, $intLength);
  134. // Deinitialize Encryption
  135. if (!mcrypt_generic_deinit($this->objMcryptModule))
  136. throw new QCryptographyException('Unable to deinitialize encryption buffer');
  137. return $strDecryptedData;
  138. }
  139. public function EncryptFile($strFile) {
  140. if (file_exists($strFile)) {
  141. $strData = file_get_contents($strFile);
  142. return $this->Encrypt($strData);
  143. } else
  144. throw new QCallerException('File does not exist: ' . $strFile);
  145. }
  146. public function DecryptFile($strFile) {
  147. if (file_exists($strFile)) {
  148. $strEncryptedData = file_get_contents($strFile);
  149. return $this->Decrypt($strEncryptedData);
  150. } else
  151. throw new QCallerException('File does not exist: ' . $strFile);
  152. }
  153. public function __destruct() {
  154. if ($this->objMcryptModule) {
  155. // Ignore All Warnings
  156. set_error_handler('QcodoHandleError', 0);
  157. $intCurrentLevel = error_reporting();
  158. error_reporting(0);
  159. mcrypt_module_close($this->objMcryptModule);
  160. error_reporting($intCurrentLevel);
  161. restore_error_handler();
  162. }
  163. }
  164. }
  165. ?>