Passed
Push — master ( 37cafd...a8b392 )
by
unknown
07:18
created

AccountStoreV1Encoder   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 17
c 1
b 0
f 0
dl 0
loc 45
rs 10
wmc 7

2 Methods

Rating   Name   Duplication   Size   Complexity  
A encode() 0 5 1
A decode() 0 20 6
1
<?php declare(strict_types=1);
2
3
namespace Files\Backend\Seafile\Model;
4
5
/**
6
 * Encoder for Account Store V1 encoding
7
 */
8
class AccountStoreV1Encoder
9
{
10
    /**
11
     * Encode an account setting value
12
     *
13
     * {@see AccountStore::encryptBackendConfigProperty()}
14
     *
15
     * @param string $value
16
     * @return string encoded
17
     */
18
    public static function encode(string $value): string
19
    {
20
        $nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
21
        $encrypted = sodium_crypto_secretbox($value, $nonce, hex2bin(FILES_ACCOUNTSTORE_V1_SECRET_KEY));
22
        return bin2hex($nonce) . bin2hex($encrypted);
23
    }
24
25
    /**
26
     * Decode an encoded account setting value
27
     *
28
     * {@see AccountStore::decryptBackendConfigProperty()}
29
     *
30
     * @param string $valueInHex
31
     * @return string decoded
32
     */
33
    public static function decode(string $valueInHex): string
34
    {
35
        $value = hex2bin($valueInHex);
36
        if (!is_string($value)) {
0 ignored issues
show
introduced by
The condition is_string($value) is always true.
Loading history...
37
            throw new \UnexpectedValueException(sprintf('Not an envelope of an encrypted value. Raw binary length of envelope is %d.', strlen($valueInHex)));
38
        }
39
        $nonce = substr($value, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
40
        if (!is_string($nonce) || strlen($nonce) !== SODIUM_CRYPTO_SECRETBOX_NONCEBYTES) {
0 ignored issues
show
introduced by
The condition is_string($nonce) is always true.
Loading history...
41
            throw new \UnexpectedValueException(sprintf('Not an encrypted value. Raw binary length is %d which is below %d.', strlen($value), SODIUM_CRYPTO_SECRETBOX_NONCEBYTES));
42
        }
43
        $encrypted = substr($value, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, strlen($value));
44
        if (!is_string($encrypted)) {
0 ignored issues
show
introduced by
The condition is_string($encrypted) is always true.
Loading history...
45
            throw new \UnexpectedValueException(sprintf('Not an encrypted value. Raw binary length is %d.', strlen($value)));
46
        }
47
        $result = sodium_crypto_secretbox_open($encrypted, $nonce, hex2bin(FILES_ACCOUNTSTORE_V1_SECRET_KEY));
48
        // Decryption failed, password might have changed
49
        if (false === $result) {
50
            throw new \UnexpectedValueException("invalid password");
51
        }
52
        return $result;
53
    }
54
}
55