Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions example/03-share-key-between-processes.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,13 @@

$message = new PlainTextMessage("Only the holder of the same key can read this.");
$cipherText = $message->encrypt($senderKey);
$ivString = (string)$message->getIv();

echo "Share this key securely: ", $sharedKeyString, PHP_EOL;
echo "Cipher text to transmit: ", $cipherText, PHP_EOL;
echo "IV to transmit: ", $message->getIv(), PHP_EOL;
echo "IV to transmit: ", $ivString, PHP_EOL;

$receivedMessage = new EncryptedMessage($cipherText, $message->getIv());
$receivedMessage = new EncryptedMessage($cipherText, $ivString);
$decryptedMessage = $receivedMessage->decrypt($receiverKey);

echo "Decrypted on the receiving side: ", $decryptedMessage, PHP_EOL;
12 changes: 11 additions & 1 deletion src/Message/AbstractMessage.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<?php
namespace GT\Cipher\Message;

use GT\Cipher\CipherException;
use GT\Cipher\InitVector;
use Stringable;

Expand All @@ -9,8 +10,17 @@ abstract class AbstractMessage implements Stringable {

public function __construct(
protected string $data,
?InitVector $iv = null,
null|string|InitVector $iv = null,
) {
if(is_string($iv)) {
$decodedIv = base64_decode($iv, true);
if($decodedIv === false) {
throw new CipherException("IV must be a valid base64 string");
}

$iv = (new InitVector())->withBytes($decodedIv);
}

$this->iv = $iv ?? new InitVector();
}

Expand Down
13 changes: 13 additions & 0 deletions test/phpunit/Message/EncryptedMessageTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,13 @@ public function testToString():void {
self::assertSame("0000", (string)$sut);
}

public function testConstruct_withBase64IvString():void {
$ivBytes = base64_decode("8Zf3DaE343vn3LLDiyTlFCS6iFP4RVMw");
$sut = new EncryptedMessage("0000", base64_encode($ivBytes));

self::assertSame($ivBytes, $sut->getIv()->getBytes());
}

/** @noinspection SpellCheckingInspection */
public function testDecrypt():void {
$iv = self::createMock(InitVector::class);
Expand Down Expand Up @@ -55,4 +62,10 @@ public function testDecrypt_wrapsSodiumFailure():void {
self::expectException(DecryptionFailureException::class);
$sut->decrypt($key);
}

public function testConstruct_invalidBase64IvString():void {
self::expectException(\GT\Cipher\CipherException::class);
self::expectExceptionMessage("IV must be a valid base64 string");
new EncryptedMessage("0000", "%%%");
}
}
Loading