Skip to content

Commit 625dc09

Browse files
committed
Enhance key handling in DefuseEncryptor and HaliteEncryptor
- Trimmed whitespace from the encryption key read from the key file in DefuseEncryptor to prevent potential issues with key formatting. - Introduced a new method in HaliteEncryptor to normalize the key file by removing leading/trailing whitespace, ensuring compatibility with Halite's hex decoder. - Added error handling for invalid key formats in HaliteEncryptor, providing clearer runtime exceptions for users.
1 parent bc81724 commit 625dc09

2 files changed

Lines changed: 27 additions & 1 deletion

File tree

src/Encryptors/DefuseEncryptor.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ private function getKey(): string
5555
{
5656
if ($this->encryptionKey === null) {
5757
if ($this->fs->exists($this->keyFile)) {
58-
$this->encryptionKey = file_get_contents($this->keyFile);
58+
$this->encryptionKey = trim(file_get_contents($this->keyFile));
5959
} else {
6060
$string = random_bytes(255);
6161
$this->encryptionKey = bin2hex($string);

src/Encryptors/HaliteEncryptor.php

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,13 +69,39 @@ private function getKey(): EncryptionKey
6969
{
7070
if ($this->encryptionKey === null) {
7171
try {
72+
$this->normalizeKeyFile();
7273
$this->encryptionKey = KeyFactory::loadEncryptionKey($this->keyFile);
7374
} catch (CannotPerformOperation $e) {
7475
$this->encryptionKey = KeyFactory::generateEncryptionKey();
7576
KeyFactory::save($this->encryptionKey, $this->keyFile);
77+
} catch (\RangeException $e) {
78+
throw new \RuntimeException(
79+
sprintf(
80+
'Invalid Halite key file at "%s": key must be hex-encoded (e.g. generated by doctrine:encrypt:generate-secret-key). Error: %s',
81+
$this->keyFile,
82+
$e->getMessage()
83+
),
84+
0,
85+
$e
86+
);
7687
}
7788
}
7889

7990
return $this->encryptionKey;
8091
}
92+
93+
/**
94+
* Removes leading/trailing whitespace (e.g. trailing newline) from the key file so Halite's hex decoder does not fail.
95+
*/
96+
private function normalizeKeyFile(): void
97+
{
98+
if (!is_file($this->keyFile) || !is_readable($this->keyFile)) {
99+
return;
100+
}
101+
$content = file_get_contents($this->keyFile);
102+
$trimmed = trim($content);
103+
if ($trimmed !== $content) {
104+
file_put_contents($this->keyFile, $trimmed);
105+
}
106+
}
81107
}

0 commit comments

Comments
 (0)