-
-
Notifications
You must be signed in to change notification settings - Fork 5k
Expand file tree
/
Copy pathEncryptionService.php
More file actions
85 lines (75 loc) · 2.22 KB
/
Copy pathEncryptionService.php
File metadata and controls
85 lines (75 loc) · 2.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
namespace OCA\Files_External\Service;
use OCP\IConfig;
use OCP\Security\ISecureRandom;
use phpseclib\Crypt\AES;
class EncryptionService {
public function __construct(
private IConfig $config,
private ISecureRandom $secureRandom,
) {
}
/**
* Encrypt passwords in the given config options
*
* @param array $options mount options
* @return array updated options
*/
public function encryptPasswords(array $options): array {
if (isset($options['password'])) {
$options['password_encrypted'] = $this->encryptPassword($options['password']);
// do not unset the password, we want to keep the keys order
// on load... because that's how the UI currently works
$options['password'] = '';
}
return $options;
}
/**
* Decrypt passwords in the given config options
*
* @param array $options mount options
* @return array updated options
*/
public function decryptPasswords(array $options): array {
// note: legacy options might still have the unencrypted password in the "password" field
if (isset($options['password_encrypted'])) {
$options['password'] = $this->decryptPassword($options['password_encrypted']);
unset($options['password_encrypted']);
}
return $options;
}
/**
* Encrypt a single password
*/
private function encryptPassword(string $password): string {
$cipher = $this->getCipher();
$iv = $this->secureRandom->generate(16);
$cipher->setIV($iv);
return base64_encode($iv . $cipher->encrypt($password));
}
/**
* Decrypts a single password
*/
private function decryptPassword(string $encryptedPassword): string {
$cipher = $this->getCipher();
$binaryPassword = base64_decode($encryptedPassword);
$iv = substr($binaryPassword, 0, 16);
$cipher->setIV($iv);
$binaryPassword = substr($binaryPassword, 16);
return $cipher->decrypt($binaryPassword);
}
/**
* Returns the encryption cipher
*/
private function getCipher(): AES {
$cipher = new AES(AES::MODE_CBC);
$cipher->setKey($this->config->getSystemValue('passwordsalt', null));
return $cipher;
}
}