Completed
Push — master ( 667c10...32c2e5 )
by Breno
03:12 queued 01:36
created

OpenCrypt::iv()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
3
namespace OpenCrypt;
4
5
class OpenCrypt
6
{
7
    /**
8
     * The cipher method. For a list of available cipher methods, use openssl_get_cipher_methods()
9
     */
10
    const CIPHER_METHOD = "AES-256-CBC";
11
12
    /**
13
     * When OPENSSL_RAW_DATA is specified, the returned data is returned as-is.
14
     */
15
    const OPTIONS = OPENSSL_RAW_DATA;
16
17
    /**
18
     * The key
19
     *
20
     * Should have been previously generated in a cryptographically safe way, like openssl_random_pseudo_bytes
21
     */
22
    private $secretKey;
23
24
    /**
25
     * IV - A non-NULL Initialization Vector.
26
     *
27
     * Encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
28
     */
29
    private $iv;
30
31 2
    public function __construct(
32
        string $secretKey,
33
        string $iv = null
34
    ) {
35 2
        $this->secretKey = hash('sha256', $secretKey);
36
37 2
        if (empty($iv)) {
38 1
            $iv = self::generateIV();
39
        }
40 2
        $this->iv = $iv;
41 2
    }
42
43 1
    public function encrypt($value) {
44 1
        $output = openssl_encrypt(
45 1
            $value,
46 1
            self::CIPHER_METHOD,
47 1
            $this->secretKey,
48 1
            self::OPTIONS,
49 1
            $this->iv
50
        );
51 1
        return base64_encode($output);
52
    }
53
54 1
    public function decrypt($value) {
55 1
        return openssl_decrypt(
56 1
            base64_decode($value),
57 1
            self::CIPHER_METHOD,
58 1
            $this->secretKey,
59 1
            self::OPTIONS,
60 1
            $this->iv
61
        );
62
    }
63
64 2
    public function iv()
65
    {
66 2
        return $this->iv;
67
    }
68
69
    /**
70
     * Generate IV
71
     *
72
     * @return int Returns a string of pseudo-random bytes, with the number of bytes expected by the method AES-256-CBC
73
     */
74 1
    public static function generateIV()
75
    {
76 1
        $ivNumBytes = openssl_cipher_iv_length(self::CIPHER_METHOD);
77 1
        return openssl_random_pseudo_bytes($ivNumBytes);
78
    }
79
80
    /**
81
     * Generate a key
82
     *
83
     * @param int $length The length of the desired string of bytes. Must be a positive integer.
84
     *
85
     * @return int Returns the hexadecimal representation of a binary data
86
     */
87 1
    public static function generateKey($length = 512)
88
    {
89 1
        $bytes = openssl_random_pseudo_bytes($length);
90 1
        return bin2hex($bytes);
91
    }
92
}
93