Skip to content

Commit 97acc3e

Browse files
committed
Added: encryptor tests
1 parent 2545455 commit 97acc3e

2 files changed

Lines changed: 62 additions & 1 deletion

File tree

src/Encryptor.php

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,12 @@ public function Decrypt(string $data): string {
4646
$salt = base64_decode($saltBase64);
4747
$secretKey = $this->generateSecretKeyFromPassphrase($this->passphrase, $salt, 32, intval($params['i']));
4848

49-
return openssl_decrypt($encryptedBase64, 'aes-256-cbc', $secretKey, 0, $salt);
49+
$decrypted = openssl_decrypt($encryptedBase64, 'aes-256-cbc', $secretKey, 0, $salt);
50+
if ($decrypted === false) {
51+
throw new \RuntimeException('Decryption failed, invalid passphrase?');
52+
}
53+
54+
return $decrypted;
5055
}
5156

5257
protected function generateSalt(int $size = 16): string {

tests/EncryptorTest.php

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
<?php
2+
3+
use AndroidSmsGateway\Encryptor;
4+
use PHPUnit\Framework\TestCase;
5+
6+
class EncryptorTest extends TestCase {
7+
public function testEncryptDecrypt(): void {
8+
$passphrase = 'MySecretPassphrase';
9+
$encryptor = new Encryptor($passphrase);
10+
11+
$originalData = 'Sensitive data here';
12+
$encryptedData = $encryptor->Encrypt($originalData);
13+
$decryptedData = $encryptor->Decrypt($encryptedData);
14+
15+
$this->assertEquals($originalData, $decryptedData, 'Decrypted data should match original data.');
16+
}
17+
18+
public function testDecryptWithWrongPassphrase(): void {
19+
$this->expectException(\RuntimeException::class);
20+
21+
$passphrase = 'MySecretPassphrase';
22+
$wrongPassphrase = 'WrongPassphrase';
23+
$encryptor = new Encryptor($passphrase);
24+
$wrongEncryptor = new Encryptor($wrongPassphrase);
25+
26+
$originalData = 'Sensitive data here';
27+
$encryptedData = $encryptor->Encrypt($originalData);
28+
29+
// Try to decrypt with wrong passphrase
30+
$wrongEncryptor->Decrypt($encryptedData);
31+
}
32+
33+
public function testDecryptWithUnsupportedAlgorithm(): void {
34+
$this->expectException(\RuntimeException::class);
35+
36+
$passphrase = 'MySecretPassphrase';
37+
$encryptor = new Encryptor($passphrase);
38+
39+
// Manually construct data with unsupported algorithm
40+
$unsupportedData = '$unsupported-algo$i=10000$fakeSalt$fakeEncryptedData';
41+
42+
$encryptor->Decrypt($unsupportedData);
43+
}
44+
45+
public function testDecryptWithMissingIterationCount(): void {
46+
$this->expectException(\RuntimeException::class);
47+
48+
$passphrase = 'MySecretPassphrase';
49+
$encryptor = new Encryptor($passphrase);
50+
51+
// Manually construct data with missing iteration count
52+
$missingIterationCountData = '$aes-256-cbc/pbkdf2-sha1$x=1$fakeSalt$fakeEncryptedData';
53+
54+
$encryptor->Decrypt($missingIterationCountData);
55+
}
56+
}

0 commit comments

Comments
 (0)