Skip to content

Commit 6d963dc

Browse files
committed
refactor
1 parent 57ea73e commit 6d963dc

File tree

1 file changed

+11
-9
lines changed

1 file changed

+11
-9
lines changed

src/Encryption.php

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,18 @@
77

88
class Encryption
99
{
10-
private $key;
10+
/**
11+
* @var AES
12+
*/
13+
private $cipher;
1114

1215
/**
1316
* Encryption constructor.
1417
* @param null $key
1518
*/
1619
public function __construct($key = null)
1720
{
21+
$this->cipher = new AES('cbc');
1822
$this->setKey($key);
1923
}
2024

@@ -24,7 +28,7 @@ public function __construct($key = null)
2428
*/
2529
public function setKey($key)
2630
{
27-
$this->key = $key;
31+
$this->cipher->setKey($key);
2832

2933
return $this;
3034
}
@@ -37,7 +41,7 @@ public function encrypt(array $data)
3741
{
3842
$iv = Random::string(16);
3943

40-
return base64_encode($iv.$this->getCipher($iv)->encrypt(json_encode($data)));
44+
return base64_encode($iv.$this->updateIv($iv)->encrypt(json_encode($data)));
4145
}
4246

4347
/**
@@ -49,19 +53,17 @@ public function decrypt($plainText)
4953
$binary = base64_decode($plainText);
5054
$iv = substr($binary, 0, 16);
5155

52-
return json_decode($this->getCipher($iv)->decrypt(substr($binary, 16)), true);
56+
return json_decode($this->updateIv($iv)->decrypt(substr($binary, 16)), true);
5357
}
5458

5559
/**
5660
* @param string $iv
5761
* @return AES
5862
*/
59-
private function getCipher($iv)
63+
private function updateIV($iv)
6064
{
61-
$cipher = new AES('cbc');
62-
$cipher->setKey($this->key);
63-
$cipher->setIV($iv);
65+
$this->cipher->setIV($iv);
6466

65-
return $cipher;
67+
return $this->cipher;
6668
}
6769
}

0 commit comments

Comments
 (0)