Completed
Push — master ( eaa085...85b293 )
by Jonathan
02:25
created

Iron::__construct()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 3
eloc 7
nc 4
nop 3
dl 0
loc 9
rs 9.6666
1
<?php
2
namespace Iron;
3
4
class Iron
5
{
6
    const DEFAULT_ENCRYPTION_METHOD = 'aes-256-cbc';
7
8
    /** @var string */
9
    private $method;
10
    /** @var callable */
11
    private $saltGenerator;
12
    /** @var callable */
13
    private $keyProvider;
14
    
15
    public function __construct(
16
        string $encryptionMethod = self::DEFAULT_ENCRYPTION_METHOD,
17
        callable $keyProvider = null,
18
        callable $saltGenerator = null
19
    ) {
20
        $this->method = $encryptionMethod;
21
        $this->keyProvider = $keyProvider ?: default_key_provider();
22
        $this->saltGenerator = $saltGenerator ?: default_salt_generator();
23
    }
24
    
25
    public function encrypt(
26
        PasswordInterface $password, 
27
        string $data, 
28
        int $ttl = 0
29
    ): Token {
30
        $salt = call_user_func($this->saltGenerator);
31
        $iv = random_bytes(openssl_cipher_iv_length($this->method));
32
33
        return new Token(
34
            $password,
35
            $salt,
36
            $iv,
37
            $this->generateCipherText($data, $password, $salt, $iv),
38
            $ttl ? time() + $ttl : $ttl,
39
            $this->keyProvider,
40
            $this->saltGenerator
41
        );
42
    }
43
44
    public function decryptToken(Token $token, PasswordInterface $password)
45
    {
46
        return openssl_decrypt(
47
            $token->getCipherText(),
48
            $this->method,
49
            call_user_func($this->keyProvider, $password, $token->getSalt()),
50
            true,
51
            $token->getIv()
52
        );
53
    }
54
55
    private function generateCipherText(
56
        string $data,
57
        PasswordInterface $password,
58
        string $salt,
59
        string $iv
60
    ) {
61
        return openssl_encrypt(
62
            $data,
63
            $this->method,
64
            call_user_func($this->keyProvider, $password, $salt),
65
            true,
66
            $iv
67
        );
68
    }
69
}
70