-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCrypt.php
114 lines (103 loc) · 2.4 KB
/
Crypt.php
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
103
104
105
106
107
108
109
110
111
112
113
114
<?php
namespace CryptTor;
use CryptTor\Strategy\StrategyInterface;
/**
* Class Crypt
*
* @author Daniel Toader <developer@danieltoader.com>
* @package Crypt
*/
class Crypt
{
/**
* Default encoding cipher algorithm
*/
const DEFAULT_ENC_ALGO = 'aes';
/**
* Default encoding cipher mode
*/
const DEFAULT_ENC_MODE = 'cbc';
/**
* Output/input format. Available options: FORMAT_RAW, FORMAT_B64 or FORMAT_HEX
* @var int
*/
private $format;
/**
* @var StrategyInterface
*/
private $strategy;
/**
* Crypt constructor.
* @param StrategyInterface $cipher
* @param int $format
*/
public function __construct(
StrategyInterface $cipher,
$format = Format::FORMAT_B64
)
{
$this->setStrategy($cipher);
$this->setFormat($format);
}
/**
* Encrypt data
*
* @param string $data
* @return string
* @throws \InvalidArgumentException
*/
public function encrypt($data)
{
$this->validateData($data);
$rawData = $this->strategy->encrypt($data);
return Format::output($rawData, $this->format);
}
/**
* Decrypt data
*
* @param string $data
* @return string
* @throws \InvalidArgumentException
*/
public function decrypt($data)
{
$this->validateData($data);
$rawData = Format::input($data, $this->format);
return $this->strategy->decrypt($rawData);
}
/**
* Set strategy method
*
* @param StrategyInterface $cipher
*/
private function setStrategy(StrategyInterface $cipher)
{
$this->strategy = $cipher;
}
/**
* Set output/input format. Available options: FORMAT_RAW, FORMAT_B64 or FORMAT_HEX
*
* @param int $format
* @throws \InvalidArgumentException
*/
private function setFormat($format)
{
Format::validate($format);
$this->format = $format;
}
/**
* Validate encrypt/decrypt data
*
* @param string $data
* @throws \InvalidArgumentException
*/
private function validateData($data)
{
if (false === is_string($data)) {
throw new \InvalidArgumentException('Data parameter must be a string');
}
if ('' === $data) {
throw new \InvalidArgumentException('Data parameter cannot be empty');
}
}
}