Encrypter::addPadding()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 7
ccs 4
cts 4
cp 1
rs 9.4285
cc 1
eloc 4
nc 1
nop 1
crap 1
1
<?php
2
namespace Graceland\SafeInCloud;
3
4
class Encrypter
5
{
6
    const BLOCK_SIZE = 16;
7
    const KEY_SIZE   = 32;
8
9
    protected $generator;
10
    protected $key;
11
12 3
    public static function generateKey()
13
    {
14 3
        return bin2hex(openssl_random_pseudo_bytes(round(static::KEY_SIZE / 2)));
15
    }
16
17 15
    public function __construct($key)
18
    {
19 15
        if (strlen($key) !== (static::KEY_SIZE)) {
20 3
            throw new \RuntimeException('The supplied encryption key must be '.(static::KEY_SIZE).' bits');
21
        }
22
23 12
        $this->key = $key;
24 12
    }
25
26
    /**
27
     * @return string
28
    */
29 3
    public function decrypt($value, $nonce)
30
    {
31 3
        $value = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $this->key, $value, MCRYPT_MODE_CBC, $nonce);
32 3
        return $this->stripPadding($value);
33
    }
34
35 3
    public function encrypt($value, $nonce)
36
    {
37 3
        $value = $this->addPadding($value);
38 3
        return mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $this->key, $value, MCRYPT_MODE_CBC, $nonce);
39
    }
40
41 6
    public function generateNonce()
42
    {
43 6
        return mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), $this->getRandomizer());
44
    }
45
46
    /**
47
     * @return string
48
    */
49 3
    public function getKey()
50
    {
51 3
        return $this->key;
52
    }
53
54 3
    protected function addPadding($value)
55
    {
56 3
        $pad   = static::BLOCK_SIZE - (strlen($value) % static::BLOCK_SIZE);
57 3
        $value = $value.str_repeat(chr($pad), $pad);
58
59 3
        return $value;
60
    }
61
62 6
    protected function getRandomizer()
63
    {
64 6
        if (defined('MCRYPT_DEV_URANDOM')) {
65 6
            return MCRYPT_DEV_URANDOM;
66
        }
67
68
        if (defined('MCRYPT_DEV_RANDOM')) {
69
            return MCRYPT_DEV_RANDOM;
70
        }
71
72
        mt_srand();
73
        return MCRYPT_RAND;
74
    }
75
76 3
    protected function isPaddingValid($pad, $value)
77
    {
78 3
        $beforePad = strlen($value) - $pad;
79 3
        return substr($value, $beforePad) == str_repeat(substr($value, -1), $pad);
80
    }
81
82
    /**
83
     * @return string
84
    */
85 3
    protected function stripPadding($value)
86
    {
87 3
        $pad = ord($value[($len = strlen($value)) - 1]);
88 3
        return $this->isPaddingValid($pad, $value) ? substr($value, 0, $len - $pad) : $value;
89
    }
90
}
91