Skip to content

Commit 660da8f

Browse files
committed
WIP unit test
1 parent 046441e commit 660da8f

File tree

2 files changed

+51
-1
lines changed

2 files changed

+51
-1
lines changed

src/Libraries/Security.php

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,14 @@
2828
*/
2929
class Security
3030
{
31+
/**
32+
* Encrypting sensitive string data
33+
*
34+
* @param string $plaintext string to encrypt
35+
*
36+
* @throws \Exception
37+
* @return bool|string
38+
*/
3139
public static function encrypt(string $plaintext): string
3240
{
3341
$plaintext = hex2bin($plaintext);
@@ -38,6 +46,24 @@ public static function encrypt(string $plaintext): string
3846
if (!$ecrypted) {
3947
throw new \Exception("failed to encrypt string");
4048
}
41-
return $ecrypted;
49+
return bin2hex($ecrypted);
50+
}
51+
52+
/**
53+
* Decrypt encrypted string
54+
*
55+
* @param string $encrypted string to decrypt
56+
*
57+
* @throws \Exception
58+
* @return bool|string
59+
*/
60+
public static function decrypt(string $encrypted): string
61+
{
62+
$binpin = hex2bin($encrypted);
63+
$decrypted = openssl_decrypt($binpin, "AES-128-CBC", env('SECURITY_KEY'), OPENSSL_ZERO_PADDING, env('SECURITY_IV_KEY'));
64+
if (!$decrypted) {
65+
throw new \Exception("failed to decrypt string");
66+
}
67+
return $decrypted;
4268
}
4369
}

tests/Libraries/SecurityTest.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Tests\Libraries;
6+
7+
use Laravel\Lumen\Testing\TestCase;
8+
use Spotlibs\PhpLib\Libraries\Security;
9+
10+
class SecurityTest extends TestCase
11+
{
12+
public function createApplication()
13+
{
14+
return require __DIR__.'/../../bootstrap/app.php';
15+
}
16+
17+
public function testEncrypt1(): void
18+
{
19+
$plain = 'beautiful soup';
20+
$encrypted = Security::encrypt($plain);
21+
$decrypted = Security::decrypt($encrypted);
22+
$this->assertEquals($plain, $decrypted);
23+
}
24+
}

0 commit comments

Comments
 (0)