Completed
Push — master ( cc3c57...4239ab )
by Jonathan
01:51
created

Iron::decryptToken()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 10
rs 9.4285
cc 1
eloc 8
nc 1
nop 2
1
<?php
2
namespace Jsq\Iron;
3
4
class Iron
5
{
6
    const DEFAULT_ENCRYPTION_METHOD = 'aes-256-cbc';
7
8
    /** @var string */
9
    private $method;
10
11
    /**
12
     * @param string $encryptionMethod
13
     */
14
    public function __construct(
15
        $encryptionMethod = self::DEFAULT_ENCRYPTION_METHOD
16
    ) {
17
        $this->method = $encryptionMethod;
18
    }
19
20
    /**
21
     * @param string|PasswordInterface $password
22
     * @param string $data
23
     * @param int $ttl
24
     *
25
     * @return Token
26
     */
27
    public function encrypt($password, $data, $ttl = 0)
28
    {
29
        $password = normalize_password($password);
30
        $salt = generate_salt();
31
        $iv = random_bytes(openssl_cipher_iv_length($this->method));
32
33
        return new Token(
34
            $password,
35
            $salt,
36
            $iv,
37
            $this->generateCipherText(json_encode($data), $password, $salt, $iv),
38
            $ttl ? time() + $ttl : $ttl
39
        );
40
    }
41
42
    /**
43
     * @param string|PasswordInterface $password
44
     * @param string|Token $data
45
     *
46
     * @return string
47
     */
48
    public function decrypt($password, $data)
49
    {
50
        $password = normalize_password($password);
51
        $token = $this->normalizeToken($password, $data);
52
53
        return $this->decryptToken($token, $password);
54
    }
55
56
    public function decryptToken(Token $token, PasswordInterface $password)
57
    {
58
        return json_decode(openssl_decrypt(
59
            $token->getCipherText(),
60
            $this->method,
61
            generate_key($password, $token->getSalt()),
62
            true,
63
            $token->getIv()
64
        ), true);
65
    }
66
67
    private function normalizeToken(PasswordInterface $password, $token)
68
    {
69
        if ($token instanceof Token) {
70
            return $token;
71
        }
72
73
        return Token::fromSealed($password, $token);
74
    }
75
76
    private function generateCipherText(
77
        $data,
78
        PasswordInterface $password,
79
        $salt,
80
        $iv
81
    ) {
82
        return openssl_encrypt(
83
            $data,
84
            $this->method,
85
            generate_key($password, $salt),
86
            true,
87
            $iv
88
        );
89
    }
90
}
91