1 <?php
2
3 namespace PayPal\Security;
4
5 /**
6 * Class Cipher
7 *
8 * Helper class to encrypt/decrypt data with secret key
9 *
10 * @package PayPal\Security
11 */
12 class Cipher
13 {
14 private $secretKey;
15
16 /**
17 * Fixed IV Size
18 */
19 const IV_SIZE = 16;
20
21 public function __construct($secretKey)
22 {
23 $this->secretKey = $secretKey;
24 }
25
26 /**
27 * Encrypts the input text using the cipher key
28 *
29 * @param $input
30 * @return string
31 */
32 public function encrypt($input)
33 {
34 // Create a random IV. Not using mcrypt to generate one, as to not have a dependency on it.
35 $iv = substr(uniqid("", true), 0, Cipher::IV_SIZE);
36 // Encrypt the data
37 $encrypted = openssl_encrypt($input, "AES-256-CBC", $this->secretKey, 0, $iv);
38 // Encode the data with IV as prefix
39 return base64_encode($iv . $encrypted);
40 }
41
42 /**
43 * Decrypts the input text from the cipher key
44 *
45 * @param $input
46 * @return string
47 */
48 public function decrypt($input)
49 {
50 // Decode the IV + data
51 $input = base64_decode($input);
52 // Remove the IV
53 $iv = substr($input, 0, Cipher::IV_SIZE);
54 // Return Decrypted Data
55 return openssl_decrypt(substr($input, Cipher::IV_SIZE), "AES-256-CBC", $this->secretKey, 0, $iv);
56 }
57 }
58