· 4 years ago · Mar 09, 2021, 11:00 AM
1<?php
2
3namespace AppBundle\Service;
4
5use Symfony\Component\DependencyInjection\ContainerInterface;
6
7/**
8 * Class Crypter
9 * @package AppBundle\Service
10 */
11class Crypter
12{
13 /**
14 * @var string $encryptMethod
15 */
16 private $encryptMethod;
17
18 /**
19 * @var string $secretKey
20 */
21 private $secretKey;
22
23 /**
24 * @var string $secretIv
25 */
26 private $secretIv;
27
28 /**
29 * @var bool|string $iv
30 */
31 private $iv;
32
33 /**
34 * @var string $key
35 */
36 private $key;
37
38 /**
39 * Crypter constructor.
40 * @param ContainerInterface $container
41 */
42 public function __construct(ContainerInterface $container)
43 {
44 $this->encryptMethod = "AES-256-CBC";
45 $this->secretKey = $container->getParameter('secretKey');
46 $this->secretIv = $container->getParameter('secretIv');
47 $this->iv = substr(hash('sha256', $this->secretIv), 0, 16);
48 $this->key = hash('sha256', $this->secretKey);
49 }
50
51 /**
52 * @param string $string
53 * @return string
54 */
55 public function encrypt(string $string): string
56 {
57 return base64_encode(openssl_encrypt($string, $this->encryptMethod, $this->key, 0, $this->iv));
58 }
59
60 /**
61 * @param string $string
62 * @return string
63 */
64 public function decrypt(string $string): string
65 {
66 return openssl_decrypt(base64_decode($string), $this->encryptMethod, $this->key, 0, $this->iv);
67 }
68}