Files
spa-api/system/crypt.php

100 lines
2.0 KiB
PHP
Raw Normal View History

2011-06-08 23:45:08 -05:00
<?php namespace System;
class Crypt {
/**
* The encryption cipher.
*
* @var string
*/
public static $cipher = 'rijndael-256';
/**
* The encryption mode.
*
* @var string
*/
public static $mode = 'cbc';
/**
* Encrypt a value using the MCrypt library.
*
* @param string $value
* @return string
*/
public static function encrypt($value)
{
2011-08-08 08:51:58 -05:00
// Seed the system random number generator so it will produce random results.
2011-08-06 20:44:13 -05:00
if (($random = static::randomizer()) === MCRYPT_RAND) mt_srand();
2011-06-08 23:45:08 -05:00
$iv = mcrypt_create_iv(static::iv_size(), $random);
2011-07-06 14:08:50 -07:00
2011-06-08 23:45:08 -05:00
$value = mcrypt_encrypt(static::$cipher, static::key(), $value, static::$mode, $iv);
return base64_encode($iv.$value);
}
/**
* Decrypt a value using the MCrypt library.
*
* @param string $value
* @return string
*/
public static function decrypt($value)
{
2011-08-08 13:14:50 -05:00
if ( ! is_string($value = base64_decode($value, true)))
2011-06-08 23:45:08 -05:00
{
throw new \Exception('Decryption error. Input value is not valid base64 data.');
}
$iv = substr($value, 0, static::iv_size());
$value = substr($value, static::iv_size());
return rtrim(mcrypt_decrypt(static::$cipher, static::key(), $value, static::$mode, $iv), "\0");
}
/**
2011-07-07 23:24:43 -05:00
* Get the random number source that should be used for the OS.
*
* @return int
*/
private static function randomizer()
{
if (defined('MCRYPT_DEV_URANDOM'))
{
return MCRYPT_DEV_URANDOM;
}
elseif (defined('MCRYPT_DEV_RANDOM'))
{
return MCRYPT_DEV_RANDOM;
}
2011-08-08 13:15:27 -05:00
return MCRYPT_RAND;
2011-07-07 23:24:43 -05:00
}
/**
* Get the application key from the application configuration file.
2011-06-08 23:45:08 -05:00
*
* @return string
*/
private static function key()
{
2011-08-08 08:51:58 -05:00
if ( ! is_null($key = Config::get('application.key')) and $key !== '') return $key;
2011-06-08 23:45:08 -05:00
2011-08-08 08:51:58 -05:00
throw new \Exception("The encryption class can not be used without an encryption key.");
2011-06-08 23:45:08 -05:00
}
/**
* Get the input vector size for the cipher and mode.
*
2011-06-16 20:33:15 -05:00
* Different ciphers and modes use varying lengths of input vectors.
*
2011-06-08 23:45:08 -05:00
* @return int
*/
private static function iv_size()
{
return mcrypt_get_iv_size(static::$cipher, static::$mode);
}
}