· 5 years ago · Mar 30, 2020, 10:16 PM
1<?php
2
3namespace Utils;
4
5use \Tmilos\JoseJwt;
6
7class Jwe
8{
9 /**
10 * @var string Secret key to be used for JWE
11 */
12 private $secretKey;
13
14 /**
15 * @param string $secretKey Secret key to be used for JWE
16 */
17 public function __construct(string $secretKey)
18 {
19 $this->secretKey = $secretKey;
20 }
21
22 /**
23 * @return Jwe Instance with key that is used on Test server
24 */
25 public static function getTestInstance(): Jwe
26 {
27 return new static(file_get_contents(APPPATH . '/config/jwe.test.secret'));
28 }
29
30 /**
31 * @return Jwe Instance with key that is used for Production server
32 */
33 public static function getProductionInstance(): Jwe
34 {
35 return new static(file_get_contents(APPPATH . '/config/jwe.secret'));
36 }
37
38 /**
39 * @param string $payload
40 *
41 * @return string
42 *
43 * @throws JoseJwt\Error\JoseJwtException
44 */
45 public function encrypt(string $payload): string
46 {
47 $factory = new JoseJwt\Context\DefaultContextFactory();
48
49 return JoseJwt\Jwe::encode(
50 $factory->get(),
51 $payload,
52 $this->secretKey,
53 JoseJwt\Jwe\JweAlgorithm::DIR,
54 JoseJwt\Jwe\JweEncryption::A256CBC_HS512
55 );
56 }
57
58 /**
59 * @param string $token Jwe token
60 *
61 * @return string
62 *
63 * @throws JoseJwt\Error\JoseJwtException
64 */
65 public function decrypt(string $token): string
66 {
67 $factory = new JoseJwt\Context\DefaultContextFactory();
68
69 return JoseJwt\Jwe::decode(
70 $factory->get(),
71 $token,
72 $this->secretKey
73 );
74 }
75}