-
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathCrypto.php
More file actions
246 lines (205 loc) · 6.91 KB
/
Copy pathCrypto.php
File metadata and controls
246 lines (205 loc) · 6.91 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
<?php
declare(strict_types=1);
namespace Bow\Security;
use RuntimeException;
class Crypto
{
/**
* The security key
*
* @var ?string
*/
private static ?string $key = null;
/**
* The security cipher
*
* @var string
*/
private static string $cipher = 'AES-256-CBC';
/**
* Header tagging the authenticated (random-IV + HMAC) payload format.
*
* The ':' is not part of the base64 alphabet, so a value carrying this
* prefix can never be confused with a legacy (base64-only) ciphertext.
*/
private const HEADER = 'BOW2:';
/**
* Header tagging an authenticated-but-unencrypted (signed) payload. The ':'
* keeps it distinguishable from an encrypted (BOW2:) or base64 value.
*/
private const SIGN_HEADER = 'BOWS1:';
/**
* The authentication tag length in bytes (HMAC-SHA256).
*/
private const MAC_LENGTH = 32;
/**
* Set the key
*
* @param string $key
* @param string|null $cipher
*/
public static function setKey(string $key, ?string $cipher = null): void
{
static::$key = $key;
if (!is_null($cipher)) {
static::$cipher = $cipher;
}
}
/**
* Encrypt data.
*
* Produces an authenticated payload: a fresh random IV is used for every
* call (so identical plaintexts yield different ciphertexts) and an
* encrypt-then-MAC HMAC-SHA256 tag protects against tampering.
*
* @param string $data
* @return string
*/
public static function encrypt(string $data): string
{
$key = static::resolveKey();
$iv_size = (int) openssl_cipher_iv_length(static::$cipher);
$iv = random_bytes($iv_size);
$cipher_text = openssl_encrypt(
$data,
static::$cipher,
static::deriveKey('enc', $key),
OPENSSL_RAW_DATA,
$iv
);
if ($cipher_text === false) {
throw new RuntimeException('Unable to encrypt the given data.');
}
$mac = hash_hmac('sha256', $iv . $cipher_text, static::deriveKey('auth', $key), true);
return self::HEADER . base64_encode($iv . $mac . $cipher_text);
}
/**
* Decrypt data.
*
* Authenticated payloads are verified before decryption and fail closed
* (return false) on a bad tag, truncation or wrong key. Values produced by
* the previous unauthenticated format are still readable for backward
* compatibility.
*
* @param string $data
*
* @return string|bool
*/
public static function decrypt(string $data): string|bool
{
$key = static::resolveKey();
if (!str_starts_with($data, self::HEADER)) {
return static::decryptLegacy($data, $key);
}
$raw = base64_decode(substr($data, strlen(self::HEADER)), true);
if ($raw === false) {
return false;
}
$iv_size = (int) openssl_cipher_iv_length(static::$cipher);
if (strlen($raw) <= $iv_size + self::MAC_LENGTH) {
return false;
}
$iv = substr($raw, 0, $iv_size);
$mac = substr($raw, $iv_size, self::MAC_LENGTH);
$cipher_text = substr($raw, $iv_size + self::MAC_LENGTH);
$calculated = hash_hmac('sha256', $iv . $cipher_text, static::deriveKey('auth', $key), true);
// Reject tampered or wrong-key payloads before touching the cipher.
if (!hash_equals($calculated, $mac)) {
return false;
}
return openssl_decrypt(
$cipher_text,
static::$cipher,
static::deriveKey('enc', $key),
OPENSSL_RAW_DATA,
$iv
);
}
/**
* Produce a tamper-proof but *readable* payload.
*
* Unlike encrypt(), the data is not enciphered — only a detached
* HMAC-SHA256 tag is prepended — so the payload stays inspectable in transit
* (e.g. a queue backend) while still being protected against tampering and
* forgery. Use when integrity matters but confidentiality does not.
*
* @param string $data
* @return string
*/
public static function sign(string $data): string
{
$mac = hash_hmac('sha256', $data, static::deriveKey('sign', static::resolveKey()), true);
return self::SIGN_HEADER . base64_encode($mac) . '.' . $data;
}
/**
* Verify a signed payload, returning the original data or false on a bad tag.
*
* Fails closed (false) on a wrong header, truncation, tampering or wrong key,
* exactly like decrypt().
*
* @param string $data
* @return string|bool
*/
public static function verify(string $data): string|bool
{
if (!str_starts_with($data, self::SIGN_HEADER)) {
return false;
}
$body = substr($data, strlen(self::SIGN_HEADER));
$dot = strpos($body, '.');
if ($dot === false) {
return false;
}
$mac = base64_decode(substr($body, 0, $dot), true);
if ($mac === false || strlen($mac) !== self::MAC_LENGTH) {
return false;
}
$payload = substr($body, $dot + 1);
$calculated = hash_hmac('sha256', $payload, static::deriveKey('sign', static::resolveKey()), true);
// Constant-time compare; reject before the caller trusts the payload.
return hash_equals($calculated, $mac) ? $payload : false;
}
/**
* Decrypt a value produced by the legacy (static IV, unauthenticated)
* format. Kept only so data encrypted before the upgrade keeps working.
*
* @param string $data
* @param string $key
* @return string|bool
*/
private static function decryptLegacy(string $data, string $key): string|bool
{
$iv_size = (int) openssl_cipher_iv_length(static::$cipher);
$iv = substr(sha1($key), 0, $iv_size);
return openssl_decrypt($data, static::$cipher, $key, 0, $iv);
}
/**
* Derive a purpose-specific 256-bit subkey from the configured key.
*
* Separating the encryption key from the authentication key (domain
* separation) is required for encrypt-then-MAC to be sound, and normalises
* an arbitrary-length configured key to a fixed strong key.
*
* @param string $context
* @param string $key
* @return string
*/
private static function deriveKey(string $context, string $key): string
{
return hash_hmac('sha256', 'BowCrypto|v2|' . $context, $key, true);
}
/**
* Resolve the configured key or fail loudly when it is missing.
*
* @return string
*/
private static function resolveKey(): string
{
if (static::$key === null || static::$key === '') {
throw new RuntimeException(
'The application security key is not set. Define security.key before using Crypto.'
);
}
return static::$key;
}
}