CakePHP
  • Documentation
    • Book
    • API
    • Videos
    • Reporting Security Issues
    • Privacy Policy
    • Logos & Trademarks
  • Business Solutions
  • Swag
  • Road Trip
  • Team
  • Community
    • Community
    • Get Involved
    • Issues (GitHub)
    • Bakery
    • Featured Resources
    • Training
    • Meetups
    • My CakePHP
    • CakeFest
    • Newsletter
    • Linkedin
    • YouTube
    • Facebook
    • Twitter
    • Mastodon
    • Help & Support
    • Forum
    • Stack Overflow
    • Slack
    • Paid Support
CakePHP

C CakePHP 2.10 API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.10
      • 4.2
      • 4.1
      • 4.0
      • 3.9
      • 3.8
      • 3.7
      • 3.6
      • 3.5
      • 3.4
      • 3.3
      • 3.2
      • 3.1
      • 3.0
      • 2.10
      • 2.9
      • 2.8
      • 2.7
      • 2.6
      • 2.5
      • 2.4
      • 2.3
      • 2.2
      • 2.1
      • 2.0
      • 1.3
      • 1.2

Packages

  • Cake
    • Cache
      • Engine
    • Configure
    • Console
      • Command
        • Task
    • Controller
      • Component
        • Acl
        • Auth
    • Core
    • Error
    • Event
    • I18n
    • Log
      • Engine
    • Model
      • Behavior
      • Datasource
        • Database
        • Session
      • Validator
    • Network
      • Email
      • Http
    • Routing
      • Filter
      • Route
    • TestSuite
      • Coverage
      • Fixture
      • Reporter
    • Utility
    • View
      • Helper
  • None

Classes

  • CakeNumber
  • CakeText
  • CakeTime
  • ClassRegistry
  • Debugger
  • File
  • Folder
  • Hash
  • Inflector
  • ObjectCollection
  • Sanitize
  • Security
  • Set
  • String
  • Validation
  • Xml
  1: <?php
  2: /**
  3:  * Core Security
  4:  *
  5:  * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  6:  * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  7:  *
  8:  * Licensed under The MIT License
  9:  * For full copyright and license information, please see the LICENSE.txt
 10:  * Redistributions of files must retain the above copyright notice.
 11:  *
 12:  * @copyright     Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
 13:  * @link          https://cakephp.org CakePHP(tm) Project
 14:  * @package       Cake.Utility
 15:  * @since         CakePHP(tm) v .0.10.0.1233
 16:  * @license       https://opensource.org/licenses/mit-license.php MIT License
 17:  */
 18: 
 19: App::uses('CakeText', 'Utility');
 20: 
 21: /**
 22:  * Security Library contains utility methods related to security
 23:  *
 24:  * @package       Cake.Utility
 25:  */
 26: class Security {
 27: 
 28: /**
 29:  * Default hash method
 30:  *
 31:  * @var string
 32:  */
 33:     public static $hashType = null;
 34: 
 35: /**
 36:  * Default cost
 37:  *
 38:  * @var string
 39:  */
 40:     public static $hashCost = '10';
 41: 
 42: /**
 43:  * Get allowed minutes of inactivity based on security level.
 44:  *
 45:  * @deprecated 3.0.0 Exists for backwards compatibility only, not used by the core
 46:  * @return int Allowed inactivity in minutes
 47:  */
 48:     public static function inactiveMins() {
 49:         switch (Configure::read('Security.level')) {
 50:             case 'high':
 51:                 return 10;
 52:             case 'medium':
 53:                 return 100;
 54:             case 'low':
 55:             default:
 56:                 return 300;
 57:         }
 58:     }
 59: 
 60: /**
 61:  * Generate authorization hash.
 62:  *
 63:  * @return string Hash
 64:  * @deprecated 2.8.1 This method was removed in 3.0.0
 65:  */
 66:     public static function generateAuthKey() {
 67:         return Security::hash(CakeText::uuid());
 68:     }
 69: 
 70: /**
 71:  * Validate authorization hash.
 72:  *
 73:  * @param string $authKey Authorization hash
 74:  * @return bool Success
 75:  * @deprecated 2.8.1 This method was removed in 3.0.0
 76:  */
 77:     public static function validateAuthKey($authKey) {
 78:         return true;
 79:     }
 80: 
 81: /**
 82:  * Create a hash from string using given method or fallback on next available method.
 83:  *
 84:  * #### Using Blowfish
 85:  *
 86:  * - Creating Hashes: *Do not supply a salt*. Cake handles salt creation for
 87:  * you ensuring that each hashed password will have a *unique* salt.
 88:  * - Comparing Hashes: Simply pass the originally hashed password as the salt.
 89:  * The salt is prepended to the hash and php handles the parsing automagically.
 90:  * For convenience the `BlowfishPasswordHasher` class is available for use with
 91:  * the AuthComponent.
 92:  * - Do NOT use a constant salt for blowfish!
 93:  *
 94:  * Creating a blowfish/bcrypt hash:
 95:  *
 96:  * ```
 97:  * $hash = Security::hash($password, 'blowfish');
 98:  * ```
 99:  *
100:  * @param string $string String to hash
101:  * @param string $type Method to use (sha1/sha256/md5/blowfish)
102:  * @param mixed $salt If true, automatically prepends the application's salt
103:  *     value to $string (Security.salt). If you are using blowfish the salt
104:  *     must be false or a previously generated salt.
105:  * @return string Hash
106:  * @link https://book.cakephp.org/2.0/en/core-utility-libraries/security.html#Security::hash
107:  */
108:     public static function hash($string, $type = null, $salt = false) {
109:         if (empty($type)) {
110:             $type = static::$hashType;
111:         }
112:         $type = strtolower($type);
113: 
114:         if ($type === 'blowfish') {
115:             return static::_crypt($string, $salt);
116:         }
117:         if ($salt) {
118:             if (!is_string($salt)) {
119:                 $salt = Configure::read('Security.salt');
120:             }
121:             $string = $salt . $string;
122:         }
123: 
124:         if (!$type || $type === 'sha1') {
125:             if (function_exists('sha1')) {
126:                 return sha1($string);
127:             }
128:             $type = 'sha256';
129:         }
130: 
131:         if ($type === 'sha256' && function_exists('mhash')) {
132:             return bin2hex(mhash(MHASH_SHA256, $string));
133:         }
134: 
135:         if (function_exists('hash')) {
136:             return hash($type, $string);
137:         }
138:         return md5($string);
139:     }
140: 
141: /**
142:  * Sets the default hash method for the Security object. This affects all objects using
143:  * Security::hash().
144:  *
145:  * @param string $hash Method to use (sha1/sha256/md5/blowfish)
146:  * @return void
147:  * @see Security::hash()
148:  */
149:     public static function setHash($hash) {
150:         static::$hashType = $hash;
151:     }
152: 
153: /**
154:  * Sets the cost for they blowfish hash method.
155:  *
156:  * @param int $cost Valid values are 4-31
157:  * @return void
158:  */
159:     public static function setCost($cost) {
160:         if ($cost < 4 || $cost > 31) {
161:             trigger_error(__d(
162:                 'cake_dev',
163:                 'Invalid value, cost must be between %s and %s',
164:                 array(4, 31)
165:             ), E_USER_WARNING);
166:             return null;
167:         }
168:         static::$hashCost = $cost;
169:     }
170: 
171: /**
172:  * Get random bytes from a secure source.
173:  *
174:  * This method will fall back to an insecure source and trigger a warning,
175:  * if it cannot find a secure source of random data.
176:  *
177:  * @param int $length The number of bytes you want.
178:  * @return string Random bytes in binary.
179:  */
180:     public static function randomBytes($length) {
181:         if (function_exists('random_bytes')) {
182:             return random_bytes($length);
183:         }
184:         if (function_exists('openssl_random_pseudo_bytes')) {
185:             return openssl_random_pseudo_bytes($length);
186:         }
187:         if (function_exists('mcrypt_create_iv')) {
188:             return mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
189:         }
190:         trigger_error(
191:             'You do not have a safe source of random data available. ' .
192:             'Install either the openssl extension, the mcrypt extension, or paragonie/random_compat. ' .
193:             'Falling back to an insecure random source.',
194:             E_USER_WARNING
195:         );
196:         $bytes = '';
197:         $byteLength = 0;
198:         while ($byteLength < $length) {
199:             $bytes .= static::hash(CakeText::uuid() . uniqid(mt_rand(), true), 'sha512', true);
200:             $byteLength = strlen($bytes);
201:         }
202:         return substr($bytes, 0, $length);
203:     }
204: 
205: /**
206:  * Runs $text through a XOR cipher.
207:  *
208:  * *Note* This is not a cryptographically strong method and should not be used
209:  * for sensitive data. Additionally this method does *not* work in environments
210:  * where suhosin is enabled.
211:  *
212:  * Instead you should use Security::encrypt() when you need strong
213:  * encryption.
214:  *
215:  * @param string $text Encrypted string to decrypt, normal string to encrypt
216:  * @param string $key Key to use
217:  * @return string Encrypted/Decrypted string
218:  * @deprecated 3.0.0 Will be removed in 3.0.
219:  */
220:     public static function cipher($text, $key) {
221:         if (empty($key)) {
222:             trigger_error(__d('cake_dev', 'You cannot use an empty key for %s', 'Security::cipher()'), E_USER_WARNING);
223:             return '';
224:         }
225: 
226:         srand((int)(float)Configure::read('Security.cipherSeed'));
227:         $out = '';
228:         $keyLength = strlen($key);
229:         for ($i = 0, $textLength = strlen($text); $i < $textLength; $i++) {
230:             $j = ord(substr($key, $i % $keyLength, 1));
231:             while ($j--) {
232:                 rand(0, 255);
233:             }
234:             $mask = rand(0, 255);
235:             $out .= chr(ord(substr($text, $i, 1)) ^ $mask);
236:         }
237:         srand();
238:         return $out;
239:     }
240: 
241: /**
242:  * Encrypts/Decrypts a text using the given key using rijndael method.
243:  *
244:  * Prior to 2.3.1, a fixed initialization vector was used. This was not
245:  * secure. This method now uses a random iv, and will silently upgrade values when
246:  * they are re-encrypted.
247:  *
248:  * @param string $text Encrypted string to decrypt, normal string to encrypt
249:  * @param string $key Key to use as the encryption key for encrypted data.
250:  * @param string $operation Operation to perform, encrypt or decrypt
251:  * @return string Encrypted/Decrypted string
252:  */
253:     public static function rijndael($text, $key, $operation) {
254:         if (empty($key)) {
255:             trigger_error(__d('cake_dev', 'You cannot use an empty key for %s', 'Security::rijndael()'), E_USER_WARNING);
256:             return '';
257:         }
258:         if (empty($operation) || !in_array($operation, array('encrypt', 'decrypt'))) {
259:             trigger_error(__d('cake_dev', 'You must specify the operation for Security::rijndael(), either encrypt or decrypt'), E_USER_WARNING);
260:             return '';
261:         }
262:         if (strlen($key) < 32) {
263:             trigger_error(__d('cake_dev', 'You must use a key larger than 32 bytes for Security::rijndael()'), E_USER_WARNING);
264:             return '';
265:         }
266:         $algorithm = MCRYPT_RIJNDAEL_256;
267:         $mode = MCRYPT_MODE_CBC;
268:         $ivSize = mcrypt_get_iv_size($algorithm, $mode);
269: 
270:         $cryptKey = substr($key, 0, 32);
271: 
272:         if ($operation === 'encrypt') {
273:             $iv = mcrypt_create_iv($ivSize, MCRYPT_RAND);
274:             return $iv . '$$' . mcrypt_encrypt($algorithm, $cryptKey, $text, $mode, $iv);
275:         }
276:         // Backwards compatible decrypt with fixed iv
277:         if (substr($text, $ivSize, 2) !== '$$') {
278:             $iv = substr($key, strlen($key) - 32, 32);
279:             return rtrim(mcrypt_decrypt($algorithm, $cryptKey, $text, $mode, $iv), "\0");
280:         }
281:         $iv = substr($text, 0, $ivSize);
282:         $text = substr($text, $ivSize + 2);
283:         return rtrim(mcrypt_decrypt($algorithm, $cryptKey, $text, $mode, $iv), "\0");
284:     }
285: 
286: /**
287:  * Generates a pseudo random salt suitable for use with php's crypt() function.
288:  * The salt length should not exceed 27. The salt will be composed of
289:  * [./0-9A-Za-z]{$length}.
290:  *
291:  * @param int $length The length of the returned salt
292:  * @return string The generated salt
293:  */
294:     protected static function _salt($length = 22) {
295:         $salt = str_replace(
296:             array('+', '='),
297:             '.',
298:             base64_encode(sha1(uniqid(Configure::read('Security.salt'), true), true))
299:         );
300:         return substr($salt, 0, $length);
301:     }
302: 
303: /**
304:  * One way encryption using php's crypt() function. To use blowfish hashing see ``Security::hash()``
305:  *
306:  * @param string $password The string to be encrypted.
307:  * @param mixed $salt false to generate a new salt or an existing salt.
308:  * @return string The hashed string or an empty string on error.
309:  */
310:     protected static function _crypt($password, $salt = false) {
311:         if ($salt === false || $salt === null || $salt === '') {
312:             $salt = static::_salt(22);
313:             $salt = vsprintf('$2a$%02d$%s', array(static::$hashCost, $salt));
314:         }
315: 
316:         $invalidCipher = (
317:             strpos($salt, '$2y$') !== 0 &&
318:             strpos($salt, '$2x$') !== 0 &&
319:             strpos($salt, '$2a$') !== 0
320:         );
321:         if ($salt === true || $invalidCipher || strlen($salt) < 29) {
322:             trigger_error(__d(
323:                 'cake_dev',
324:                 'Invalid salt: %s for %s Please visit http://www.php.net/crypt and read the appropriate section for building %s salts.',
325:                 array($salt, 'blowfish', 'blowfish')
326:             ), E_USER_WARNING);
327:             return '';
328:         }
329:         return crypt($password, $salt);
330:     }
331: 
332: /**
333:  * Encrypt a value using AES-256.
334:  *
335:  * *Caveat* You cannot properly encrypt/decrypt data with trailing null bytes.
336:  * Any trailing null bytes will be removed on decryption due to how PHP pads messages
337:  * with nulls prior to encryption.
338:  *
339:  * @param string $plain The value to encrypt.
340:  * @param string $key The 256 bit/32 byte key to use as a cipher key.
341:  * @param string $hmacSalt The salt to use for the HMAC process. Leave null to use Security.salt.
342:  * @return string Encrypted data.
343:  * @throws CakeException On invalid data or key.
344:  */
345:     public static function encrypt($plain, $key, $hmacSalt = null) {
346:         static::_checkKey($key, 'encrypt()');
347: 
348:         if ($hmacSalt === null) {
349:             $hmacSalt = Configure::read('Security.salt');
350:         }
351: 
352:         // Generate the encryption and hmac key.
353:         $key = substr(hash('sha256', $key . $hmacSalt), 0, 32);
354: 
355:         if (Configure::read('Security.useOpenSsl')) {
356:             $method = 'AES-256-CBC';
357:             $ivSize = openssl_cipher_iv_length($method);
358:             $iv = openssl_random_pseudo_bytes($ivSize);
359:             $padLength = (int)ceil((strlen($plain) ?: 1) / $ivSize) * $ivSize;
360:             $ciphertext = openssl_encrypt(str_pad($plain, $padLength, "\0"), $method, $key, true, $iv);
361:             // Remove the PKCS#7 padding block for compatibility with mcrypt.
362:             // Since we have padded the provided data with \0, the final block contains only padded bytes.
363:             // So it can be removed safely.
364:             $ciphertext = $iv . substr($ciphertext, 0, -$ivSize);
365:         } else {
366:             $algorithm = MCRYPT_RIJNDAEL_128;
367:             $mode = MCRYPT_MODE_CBC;
368:             $ivSize = mcrypt_get_iv_size($algorithm, $mode);
369:             $iv = mcrypt_create_iv($ivSize, MCRYPT_DEV_URANDOM);
370:             $ciphertext = $iv . mcrypt_encrypt($algorithm, $key, $plain, $mode, $iv);
371:         }
372: 
373:         $hmac = hash_hmac('sha256', $ciphertext, $key);
374:         return $hmac . $ciphertext;
375:     }
376: 
377: /**
378:  * Check the encryption key for proper length.
379:  *
380:  * @param string $key Key to check.
381:  * @param string $method The method the key is being checked for.
382:  * @return void
383:  * @throws CakeException When key length is not 256 bit/32 bytes
384:  */
385:     protected static function _checkKey($key, $method) {
386:         if (strlen($key) < 32) {
387:             throw new CakeException(__d('cake_dev', 'Invalid key for %s, key must be at least 256 bits (32 bytes) long.', $method));
388:         }
389:     }
390: 
391: /**
392:  * Decrypt a value using AES-256.
393:  *
394:  * @param string $cipher The ciphertext to decrypt.
395:  * @param string $key The 256 bit/32 byte key to use as a cipher key.
396:  * @param string $hmacSalt The salt to use for the HMAC process. Leave null to use Security.salt.
397:  * @return string Decrypted data. Any trailing null bytes will be removed.
398:  * @throws CakeException On invalid data or key.
399:  */
400:     public static function decrypt($cipher, $key, $hmacSalt = null) {
401:         static::_checkKey($key, 'decrypt()');
402:         if (empty($cipher)) {
403:             throw new CakeException(__d('cake_dev', 'The data to decrypt cannot be empty.'));
404:         }
405:         if ($hmacSalt === null) {
406:             $hmacSalt = Configure::read('Security.salt');
407:         }
408: 
409:         // Generate the encryption and hmac key.
410:         $key = substr(hash('sha256', $key . $hmacSalt), 0, 32);
411: 
412:         // Split out hmac for comparison
413:         $macSize = 64;
414:         $hmac = substr($cipher, 0, $macSize);
415:         $cipher = substr($cipher, $macSize);
416: 
417:         $compareHmac = hash_hmac('sha256', $cipher, $key);
418:         if ($hmac !== $compareHmac) {
419:             return false;
420:         }
421: 
422:         if (Configure::read('Security.useOpenSsl')) {
423:             $method = 'AES-256-CBC';
424:             $ivSize = openssl_cipher_iv_length($method);
425:             $iv = substr($cipher, 0, $ivSize);
426:             $cipher = substr($cipher, $ivSize);
427:             // Regenerate PKCS#7 padding block
428:             $padding = openssl_encrypt('', $method, $key, true, substr($cipher, -$ivSize));
429:             $plain = openssl_decrypt($cipher . $padding, $method, $key, true, $iv);
430:         } else {
431:             $algorithm = MCRYPT_RIJNDAEL_128;
432:             $mode = MCRYPT_MODE_CBC;
433:             $ivSize = mcrypt_get_iv_size($algorithm, $mode);
434:             $iv = substr($cipher, 0, $ivSize);
435:             $cipher = substr($cipher, $ivSize);
436:             $plain = mcrypt_decrypt($algorithm, $key, $cipher, $mode, $iv);
437:         }
438: 
439:         return rtrim($plain, "\0");
440:     }
441: 
442: }
443: 
OpenHub
Rackspace
Rackspace
  • Business Solutions
  • Showcase
  • Documentation
  • Book
  • API
  • Videos
  • Reporting Security Issues
  • Privacy Policy
  • Logos & Trademarks
  • Community
  • Get Involved
  • Issues (GitHub)
  • Bakery
  • Featured Resources
  • Training
  • Meetups
  • My CakePHP
  • CakeFest
  • Newsletter
  • Linkedin
  • YouTube
  • Facebook
  • Twitter
  • Mastodon
  • Help & Support
  • Forum
  • Stack Overflow
  • Slack
  • Paid Support

Generated using CakePHP API Docs