-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCrypto.php
More file actions
102 lines (84 loc) · 2.43 KB
/
Crypto.php
File metadata and controls
102 lines (84 loc) · 2.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
<?php // vim:ts=3:sts=3:sw=3:et:
/**
* Encryption/decryption module
*
* PHP Version 5
*
* @category PHP
* @package MindFrame2
* @author Bryan C. Geraghty <bryan@ravensight.org>
* @copyright 2005-2011 Bryan C. Geraghty
* @license http://www.gnu.org/licenses/lgpl-3.0.txt GNU LGPL
* @link https://github.com/archwisp/MindFrame2
*/
/**
* Encryption/decryption module
*
* @category PHP
* @package MindFrame2
* @author Bryan C. Geraghty <bryan@ravensight.org>
* @license http://www.gnu.org/licenses/lgpl-3.0.txt GNU LGPL
* @link https://github.com/archwisp/MindFrame2
*/
class MindFrame2_Crypto
{
const RIJNDAEL_256 = MCRYPT_RIJNDAEL_256;
const MODE_CBC = MCRYPT_MODE_CBC;
private $_algorithm;
private $_mode;
public function __construct($algorithm, $mode)
{
$this->_algorithm = $algorithm;
$this->_mode = $mode;
}
public function encrypt($plaintext, $key, $iv)
{
return mcrypt_encrypt($this->_algorithm,
$key, $plaintext, $this->_mode, $iv);
}
public function decrypt($ciphertext, $key, $iv)
{
return mcrypt_decrypt($this->_algorithm,
$key, $ciphertext, $this->_mode, $iv);
}
public function getBlockSize()
{
return mcrypt_get_iv_size($this->_algorithm, $this->_mode);
}
public function generateIv()
{
return mcrypt_create_iv($this->getBlockSize(), MCRYPT_DEV_URANDOM);
}
public function getKeySize()
{
return mcrypt_get_key_size($this->_algorithm, $this->_mode);
}
public function padWithNulls($plaintext)
{
return str_pad($plaintext, $this->getBlockSize(), "\x0");
}
public function padWithPkcs7($plaintext)
{
$block_size = $this->getBlockSize();
if ($block_size > 255)
{
throw new RuntimeException('PKCS7 padding is only well defined for block sizes smaller than 256 bits');
}
$pad_length = ($block_size - (strlen($plaintext) % $block_size));
return $plaintext . str_repeat(chr($pad_length), $pad_length);
}
public function trimNulls($plaintext)
{
return rtrim($plaintext, "\x0");
}
public function trimPkcs7($plaintext)
{
$pad_char = substr($plaintext, -1);
$pad_length = ord($pad_char);
if (substr($plaintext, -$pad_length) !== str_repeat($pad_char, $pad_length))
{
throw new RuntimeException('Invalid pad value');
}
return substr($plaintext, 0, -$pad_length);
}
}