Skip to content

Commit b04763d

Browse files
author
Greg Bowler
committed
wip: first exception handling for #10
1 parent 84844a2 commit b04763d

File tree

2 files changed

+41
-10
lines changed

2 files changed

+41
-10
lines changed

src/Message/EncryptedMessage.php

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -9,17 +9,27 @@ public function decrypt(
99
PrivateKey $receiverPrivateKey,
1010
PublicKey $senderPublicKey,
1111
):PlainTextMessage {
12-
$unlockingKeyPair = sodium_crypto_box_keypair_from_secretkey_and_publickey(
13-
$receiverPrivateKey->getBytes(),
14-
$senderPublicKey->getBytes(),
15-
);
16-
$decrypted = sodium_crypto_box_open(
17-
base64_decode($this->data),
18-
$this->iv->getBytes(),
19-
$unlockingKeyPair,
20-
);
12+
$errorMessage = "Error decrypting cipher message";
13+
$decrypted = false;
14+
15+
try {
16+
$unlockingKeyPair = sodium_crypto_box_keypair_from_secretkey_and_publickey(
17+
$receiverPrivateKey->getBytes(),
18+
$senderPublicKey->getBytes(),
19+
);
20+
$decrypted = sodium_crypto_box_open(
21+
base64_decode($this->data),
22+
$this->iv->getBytes(),
23+
$unlockingKeyPair,
24+
);
25+
}
26+
catch(\SodiumException $exception) {
27+
// TODO: Issue #10 - this is one of the exceptions, but I think it makes sense to parse the message and extract the meaningful information.
28+
// Friendly exception messages are the future!
29+
$errorMessage = $exception->getMessage();
30+
}
2131
if($decrypted === false) {
22-
throw new DecryptionFailureException("Error decrypting cipher message");
32+
throw new DecryptionFailureException($errorMessage);
2333
}
2434
return new PlainTextMessage(
2535
$decrypted,

test/phpunit/Message/EncryptedMessageTest.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,4 +51,25 @@ public function testDecrypt_failure():void {
5151
$senderPublicKey,
5252
);
5353
}
54+
55+
public function testDecrypt_incorrectKeySize():void {
56+
$iv = self::createMock(InitVector::class);
57+
$iv->method("getBytes")
58+
->willReturn(str_repeat("0", SODIUM_CRYPTO_BOX_NONCEBYTES - 2));
59+
$sut = new EncryptedMessage("badly formed data", $iv);
60+
61+
$receiverPrivateKey = self::createMock(PrivateKey::class);
62+
$receiverPrivateKey->method("getBytes")
63+
->willReturn(str_repeat("0", SODIUM_CRYPTO_BOX_SECRETKEYBYTES));
64+
$senderPublicKey = self::createMock(PublicKey::class);
65+
$senderPublicKey->method("getBytes")
66+
->willReturn(str_repeat("0", SODIUM_CRYPTO_BOX_PUBLICKEYBYTES));
67+
68+
self::expectExceptionMessage("sodium_crypto_box_open(): Argument #2 (\$nonce) must be SODIUM_CRYPTO_BOX_NONCEBYTES bytes long");
69+
self::expectException(DecryptionFailureException::class);
70+
$sut->decrypt(
71+
$receiverPrivateKey,
72+
$senderPublicKey,
73+
);
74+
}
5475
}

0 commit comments

Comments
 (0)