From fe4fd63d0fcea8ebaaaa7873d82c0ec930cdb0f5 Mon Sep 17 00:00:00 2001 From: Hannes Papenberg Date: Thu, 12 Nov 2026 23:06:12 +0100 Subject: [PATCH] Do not expose the raw key through Key::getPublic() in the Crypto cipher defuse/php-encryption is symmetric, but Crypto::generateKey() stored the raw 32-byte secret as the public part of the key. Code that treats public keys as shareable (logging, sending to clients) leaked the full key. The cipher never reads the public part, so leave it empty. Co-Authored-By: Claude Opus 5.5 --- Tests/Cipher/CryptoTest.php | 7 +++++-- docs/overview.md | 7 ++++--- src/Cipher/Crypto.php | 4 ++-- 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/Tests/Cipher/CryptoTest.php b/Tests/Cipher/CryptoTest.php index 6499e78d..ab3b340e 100644 --- a/Tests/Cipher/CryptoTest.php +++ b/Tests/Cipher/CryptoTest.php @@ -90,8 +90,11 @@ public function testGenerateKey() // Assert that the key is the correct type. $this->assertInstanceOf(Key::class, $key); - // Assert the public key is the expected length - $this->assertSame(DefuseKey::KEY_BYTE_SIZE, Binary::strlen($key->getPublic())); + // Assert the key has no public part, as the raw key bytes must not be exposed through getPublic() + $this->assertSame('', $key->getPublic()); + + // Assert the private key is a usable key + $this->assertInstanceOf(DefuseKey::class, DefuseKey::loadFromAsciiSafeString($key->getPrivate())); // Assert the key is of the correct type. $this->assertSame('crypto', $key->getType()); diff --git a/docs/overview.md b/docs/overview.md index 7a7f3ce5..5da15c60 100644 --- a/docs/overview.md +++ b/docs/overview.md @@ -54,9 +54,10 @@ $key = new Key('crypto', $secret, ''); $crypt = new Crypt(new Crypto(), $key); ``` -`Crypto::generateKey()` currently puts the raw key bytes into the key object's *public* field. That -field is meaningless for a symmetric algorithm, so treat `getPublic()` on a `crypto` key as secret -material and never log, transmit or store it. +The algorithm is symmetric, so a `crypto` key has no public part: since 4.1 `Crypto::generateKey()` +sets it to an empty string. Earlier releases put the raw key bytes into the *public* field; treat +`getPublic()` of keys generated by those releases as secret material and never log, transmit or +store it. Only the private part is needed to encrypt and decrypt. ## Handling failures diff --git a/src/Cipher/Crypto.php b/src/Cipher/Crypto.php index a1c19369..818f3bb4 100644 --- a/src/Cipher/Crypto.php +++ b/src/Cipher/Crypto.php @@ -103,8 +103,8 @@ public function generateKey(array $options = []) throw new InvalidKeyException('Cannot safely create a key', $ex->getCode(), $ex); } - // Create the new encryption key object. - return new Key('crypto', $public->saveToAsciiSafeString(), $public->getRawBytes()); + // Create the new encryption key object. The cipher is symmetric, so there is no public part. + return new Key('crypto', $public->saveToAsciiSafeString(), ''); } /**