1 <?php
2 /**
3 * Crypto.php
4 *
5 * @author Elvyrra SAS
6 * @license http://rem.mit-license.org/ MIT
7 */
8
9 namespace Hawk;
10
11 /**
12 * This class contains cryptography functions
13 *
14 * @package Security
15 */
16 class Crypto{
17
18 /**
19 * Encode a string with AES 256 algorithm
20 *
21 * @param string $data The data to encrypt
22 * @param string $key The encryption key
23 * @param string $iv The initialization vector for encryption
24 *
25 * @return string The encrypted data
26 */
27 public static function aes256Encode($data, $key = CRYPTO_KEY, $iv = CRYPTO_IV){
28 $block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
29 $pad = $block - (strlen($data) % $block);
30 $data .= str_repeat(chr($pad), $pad);
31
32 $result = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, $iv);
33 $result = base64_encode($result);
34 return $result;
35 }
36
37 /**
38 * Decode with AES 256 algorithm
39 *
40 * @param string $data The data to decrypt
41 * @param string $key The decryption key
42 * @param string $iv The initialization vector for decryption
43 *
44 * @return string The decrypted data
45 */
46 public static function aes256Decode($data, $key = CRYPTO_KEY, $iv = CRYPTO_IV){
47 $code = base64_decode($data);
48 $code = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $code, MCRYPT_MODE_CBC, $iv);
49 $code = substr($code, 0, -(ord($code[strlen($code)-1])));
50 return $code;
51 }
52
53
54 /**
55 * Hash a string with a salt
56 *
57 * @param string $data The data to hash
58 * @param string $salt The salt to use before hashing
59 *
60 * @return string The hashed data
61 */
62 public static function saltHash($data, $salt = CRYPTO_SALT){
63 return sha1($salt . $data . $salt);
64 }
65
66
67 /**
68 * Generate random key
69 *
70 * @param int $length The length of the generated key
71 *
72 * @return string the generated key
73 */
74 public static function generateKey($length){
75 $result = '';
76 for ($i=0; $i < $length; $i++) {
77 do{
78 $char = chr(mt_rand(33, 126));
79 }while($char == '\\');
80
81 $result .= $char;
82 }
83
84 return $result;
85 }
86 }