-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAES.php
More file actions
82 lines (74 loc) · 1.79 KB
/
AES.php
File metadata and controls
82 lines (74 loc) · 1.79 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
<?php
/**
* Created by PhpStorm.
* User: overnic
* Date: 2018/4/20
* Time: 16:40
*/
namespace OverNick\Support;
/**
* Class AES
*
* @package OverNick\Payment\Kernel\Tools
*/
class AES
{
/**
* @param string $text
* @param string $key
* @param string $iv
* @param int $option
*
* @return string
*/
public static function encrypt($text, $key, $iv, $option = OPENSSL_RAW_DATA)
{
self::validateKey($key);
self::validateIv($iv);
return openssl_encrypt($text, self::getMode($key), $key, $option, $iv);
}
/**
* @param string $cipherText
* @param string $key
* @param string $iv
* @param int $option
* @param string|null $method
*
* @return string
*/
public static function decrypt($cipherText,$key,$iv,$option = OPENSSL_RAW_DATA, $method = null)
{
self::validateKey($key);
self::validateIv($iv);
return openssl_decrypt($cipherText, $method ?: self::getMode($key), $key, $option, $iv);
}
/**
* @param string $key
*
* @return string
*/
public static function getMode($key)
{
return 'aes-'.(8 * strlen($key)).'-cbc';
}
/**
* @param string $key
*/
public static function validateKey($key)
{
if (!in_array(strlen($key), [16, 24, 32], true)) {
throw new \InvalidArgumentException(sprintf('Key length must be 16, 24, or 32 bytes; got key len (%s).', strlen($key)));
}
}
/**
* @param string $iv
*
* @throws \InvalidArgumentException
*/
public static function validateIv($iv)
{
if (!empty($iv) && 16 !== strlen($iv)) {
throw new \InvalidArgumentException('IV length must be 16 bytes.');
}
}
}