|
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)) { |
|
|
|
|
|
|
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) { |
|
|
|
|
|
|
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)) { |
|
|
|
|
|
|
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
|
|
|
|