1+ <?php
2+
3+ namespace AndroidSmsGateway ;
4+
5+ class Encryptor {
6+ protected string $ passphrase ;
7+ protected int $ iterationCount ;
8+
9+ /**
10+ * Encryptor constructor.
11+ * @param string $passphrase Passphrase to use for encryption
12+ * @param int $iterationCount Iteration count
13+ */
14+ public function __construct (
15+ string $ passphrase ,
16+ int $ iterationCount = 75000
17+ ) {
18+ $ this ->passphrase = $ passphrase ;
19+ $ this ->iterationCount = $ iterationCount ;
20+ }
21+
22+ public function Encrypt (string $ data ): string {
23+ $ salt = $ this ->generateSalt ();
24+ $ secretKey = $ this ->generateSecretKeyFromPassphrase ($ this ->passphrase , $ salt , 32 , $ this ->iterationCount );
25+
26+ return sprintf (
27+ '$aes-256-cbc/pbkdf2-sha1$i=%d$%s$%s ' ,
28+ $ this ->iterationCount ,
29+ base64_encode ($ salt ),
30+ openssl_encrypt ($ data , 'aes-256-cbc ' , $ secretKey , 0 , $ salt )
31+ );
32+ }
33+
34+ public function Decrypt (string $ data ): string {
35+ list ($ _ , $ algo , $ paramsStr , $ saltBase64 , $ encryptedBase64 ) = explode ('$ ' , $ data );
36+
37+ if ($ algo !== 'aes-256-cbc/pbkdf2-sha1 ' ) {
38+ throw new \RuntimeException ('Unsupported algorithm ' );
39+ }
40+
41+ $ params = $ this ->parseParams ($ paramsStr );
42+ if (empty ($ params ['i ' ])) {
43+ throw new \RuntimeException ('Missing iteration count ' );
44+ }
45+
46+ $ salt = base64_decode ($ saltBase64 );
47+ $ secretKey = $ this ->generateSecretKeyFromPassphrase ($ this ->passphrase , $ salt , 32 , intval ($ params ['i ' ]));
48+
49+ return openssl_decrypt ($ encryptedBase64 , 'aes-256-cbc ' , $ secretKey , 0 , $ salt );
50+ }
51+
52+ protected function generateSalt (int $ size = 16 ): string {
53+ return random_bytes ($ size );
54+ }
55+
56+ protected function generateSecretKeyFromPassphrase (
57+ string $ passphrase ,
58+ string $ salt ,
59+ int $ keyLength = 32 ,
60+ int $ iterationCount = 75000
61+ ): string {
62+ return hash_pbkdf2 ('sha1 ' , $ passphrase , $ salt , $ iterationCount , $ keyLength , true );
63+ }
64+
65+ /**
66+ * @return array<string, string>
67+ */
68+ protected function parseParams (string $ params ): array {
69+ $ keyValuePairs = explode (', ' , $ params );
70+ $ result = [];
71+ foreach ($ keyValuePairs as $ pair ) {
72+ list ($ key , $ value ) = explode ('= ' , $ pair , 2 );
73+ $ result [$ key ] = $ value ;
74+ }
75+ return $ result ;
76+ }
77+ }
0 commit comments