OpenCrypt::generateIV()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 3
cts 3
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
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
        $this->iv = $iv ?: self::generateIV();
38 2
    }
39
40 1
    public function encrypt(string $value) {
41 1
        $output = openssl_encrypt(
42 1
            $value,
43 1
            self::CIPHER_METHOD,
44 1
            $this->secretKey,
45 1
            self::OPTIONS,
46 1
            $this->iv
47
        );
48 1
        return base64_encode($output);
49
    }
50
51 1
    public function decrypt(string $value) {
52 1
        return openssl_decrypt(
53 1
            base64_decode($value),
54 1
            self::CIPHER_METHOD,
55 1
            $this->secretKey,
56 1
            self::OPTIONS,
57 1
            $this->iv
58
        );
59
    }
60
61 2
    public function iv()
62
    {
63 2
        return $this->iv;
64
    }
65
66
    /**
67
     * Generate IV
68
     *
69
     * @return int Returns a string of pseudo-random bytes, with the number of bytes expected by the method AES-256-CBC
70
     */
71 1
    public static function generateIV()
72
    {
73 1
        $ivNumBytes = openssl_cipher_iv_length(self::CIPHER_METHOD);
74 1
        return openssl_random_pseudo_bytes($ivNumBytes);
75
    }
76
77
    /**
78
     * Generate a key
79
     *
80
     * @param int $length The length of the desired string of bytes. Must be a positive integer.
81
     *
82
     * @return int Returns the hexadecimal representation of a binary data
83
     */
84 1
    public static function generateKey($length = 512)
85
    {
86 1
        $bytes = openssl_random_pseudo_bytes($length);
87 1
        return bin2hex($bytes);
88
    }
89
}
90