1: <?php
2: namespace Hyperwallet\Util;
3: use GuzzleHttp\Client;
4: use GuzzleHttp\Exception\BadResponseException;
5: use GuzzleHttp\Exception\ConnectException;
6: use GuzzleHttp\UriTemplate\UriTemplate;
7: use Hyperwallet\Exception\HyperwalletApiException;
8: use Hyperwallet\Exception\HyperwalletException;
9: use Hyperwallet\Model\BaseModel;
10: use Hyperwallet\Response\ErrorResponse;
11: use Jose\Component\Core\AlgorithmManager;
12: use Jose\Component\Core\JWK;
13: use Jose\Component\Signature\Algorithm\RS256;
14: use Jose\Component\Signature\JWSBuilder;
15: use Jose\Component\Signature\JWSVerifier;
16: use Jose\Component\Signature\Serializer\CompactSerializer as JWSCompactSerializer;
17: use Jose\Component\Encryption\Algorithm\KeyEncryption\RSAOAEP256;
18: use Jose\Component\Encryption\Algorithm\ContentEncryption\A256CBCHS512;
19: use Jose\Component\Encryption\JWEBuilder;
20: use Jose\Component\Encryption\JWEDecrypter;
21: use Jose\Component\Encryption\Serializer\CompactSerializer as JWECompactSerializer;
22:
23: /**
24: * The encryption service for Hyperwallet client's requests/responses
25: *
26: * @package Hyperwallet\Util
27: */
28: class HyperwalletEncryption {
29:
30: /**
31: * String that can be a URL or path to file with client JWK set
32: *
33: * @var string
34: */
35: private $clientPrivateKeySetLocation;
36:
37: /**
38: * String that can be a URL or path to file with hyperwallet JWK set
39: *
40: * @var string
41: */
42: private $hyperwalletKeySetLocation;
43:
44: /**
45: * JWE encryption algorithm, by default value = RSA-OAEP-256
46: *
47: * @var string
48: */
49: private $encryptionAlgorithm;
50:
51: /**
52: * JWS signature algorithm, by default value = RS256
53: *
54: * @var string
55: */
56: private $signAlgorithm;
57:
58: /**
59: * JWE encryption method, by default value = A256CBC-HS512
60: *
61: * @var string
62: */
63: private $encryptionMethod;
64:
65: /**
66: * Minutes when JWS signature is valid, by default value = 5
67: *
68: * @var integer
69: */
70: private $jwsExpirationMinutes;
71:
72: /**
73: * JWS key id header param
74: *
75: * @var string
76: */
77: private $jwsKid;
78:
79: /**
80: * JWE key id header param
81: *
82: * @var string
83: */
84: private $jweKid;
85:
86: /**
87: * Creates a instance of the HyperwalletEncryption
88: *
89: * @param string $clientPrivateKeySetLocation String that can be a URL or path to file with client JWK set
90: * @param string $hyperwalletKeySetLocation String that can be a URL or path to file with hyperwallet JWK set
91: * @param string $encryptionAlgorithm JWE encryption algorithm, by default value = RSA-OAEP-256
92: * @param string $signAlgorithm JWS signature algorithm, by default value = RS256
93: * @param string $encryptionMethod JWE encryption method, by default value = A256CBC-HS512
94: * @param integer $jwsExpirationMinutes Minutes when JWS signature is valid, by default value = 5
95: */
96: public function __construct($clientPrivateKeySetLocation, $hyperwalletKeySetLocation,
97: $encryptionAlgorithm = 'RSA-OAEP-256', $signAlgorithm = 'RS256', $encryptionMethod = 'A256CBC-HS512',
98: $jwsExpirationMinutes = 5) {
99: $this->clientPrivateKeySetLocation = $clientPrivateKeySetLocation;
100: $this->hyperwalletKeySetLocation = $hyperwalletKeySetLocation;
101: $this->encryptionAlgorithm = $encryptionAlgorithm;
102: $this->signAlgorithm = $signAlgorithm;
103: $this->encryptionMethod = $encryptionMethod;
104: $this->jwsExpirationMinutes = $jwsExpirationMinutes;
105: }
106:
107: /**
108: * Makes an encrypted request : 1) signs the request body; 2) encrypts payload after signature
109: *
110: * @param string $body The request body to be encrypted
111: * @return string
112: *
113: * @throws HyperwalletException
114: */
115: public function encrypt($body) {
116: $privateJwsKey = $this->getPrivateJwsKey();
117: $payload = json_encode($body);
118: $jws = (new JWSBuilder(new AlgorithmManager([new RS256()])))->create()
119: ->withPayload($payload)
120: ->addSignature($privateJwsKey, ['alg' => $this->signAlgorithm, 'kid' => $this->jwsKid, 'exp' => $this->getSignatureExpirationTime()])
121: ->build();
122: $jwsToken = (new JWSCompactSerializer())->serialize($jws);
123:
124: $publicJweKey = $this->getPublicJweKey();
125: $jwe = (new JWEBuilder(
126: new AlgorithmManager([new RSAOAEP256()]),
127: new AlgorithmManager([new A256CBCHS512()])
128: ))
129: ->create()->withPayload($jwsToken)
130: ->withSharedProtectedHeader(['alg' => $this->encryptionAlgorithm, 'enc' => $this->encryptionMethod, 'kid' => $this->jweKid])
131: ->addRecipient($publicJweKey)->build();
132: return (new JWECompactSerializer())->serialize($jwe, 0);
133: }
134:
135: /**
136: * Decrypts encrypted response : 1) decrypts the request body; 2) verifies the payload signature
137: *
138: * @param string $body The response body to be decrypted
139: * @return string
140: *
141: * @throws HyperwalletException
142: */
143: public function decrypt($body) {
144: $privateJweKey = $this->getPrivateJweKey();
145: $serializer = new JWECompactSerializer();
146: $jwe = $serializer->unserialize($body);
147: $this->checkJweHeaderAlgorithm($jwe->getSharedProtectedHeader());
148: $decrypted = (new JWEDecrypter(
149: new AlgorithmManager([new RSAOAEP256()]),
150: new AlgorithmManager([new A256CBCHS512()])
151: ))->decryptUsingKey($jwe, $privateJweKey, 0);
152: if ($decrypted instanceof \Jose\Component\Encryption\JWE) {
153: $jwe = $decrypted;
154: }
155: if (!$jwe->getPayload()) {
156: throw new HyperwalletException('Payload decryption failed');
157: }
158:
159: $publicJwsKey = $this->getPublicJwsKey();
160: $jwsToVerify = (new JWSCompactSerializer())->unserialize($jwe->getPayload());
161: $header = $jwsToVerify->getSignature(0)->getProtectedHeader();
162: $this->checkJwsExpiration($header);
163: if (!(new JWSVerifier(new AlgorithmManager([new RS256()])))->verifyWithKey($jwsToVerify, $publicJwsKey, 0)) {
164: throw new HyperwalletException('Signature verification failed');
165: }
166: $claims = json_decode($jwsToVerify->getPayload(), true);
167: return is_array($claims) ? $claims : array('scalar' => $claims);
168: }
169:
170: /**
171: * Retrieves JWS RSA private key with algorithm = $this->signAlgorithm
172: *
173: * @return RSA
174: *
175: * @throws HyperwalletException
176: */
177: private function getPrivateJwsKey() {
178: $privateKeyData = $this->getJwk($this->clientPrivateKeySetLocation, $this->signAlgorithm);
179: $this->jwsKid = $privateKeyData['kid'];
180: return new JWK($privateKeyData);
181: }
182:
183: /**
184: * Retrieves JWE RSA public key with algorithm = $this->encryptionAlgorithm
185: *
186: * @return RSA
187: *
188: * @throws HyperwalletException
189: */
190: private function getPublicJweKey() {
191: $publicKeyData = $this->getJwk($this->hyperwalletKeySetLocation, $this->encryptionAlgorithm);
192: $this->jweKid = $publicKeyData['kid'];
193: return new JWK($this->convertPrivateKeyToPublic($publicKeyData));
194: }
195:
196: /**
197: * Retrieves JWE RSA private key with algorithm = $this->encryptionAlgorithm
198: *
199: * @return RSA
200: *
201: * @throws HyperwalletException
202: */
203: private function getPrivateJweKey() {
204: $privateKeyData = $this->getJwk($this->clientPrivateKeySetLocation, $this->encryptionAlgorithm);
205: return new JWK($privateKeyData);
206: }
207:
208: /**
209: * Retrieves JWS RSA public key with algorithm = $this->signAlgorithm
210: *
211: * @return RSA
212: *
213: * @throws HyperwalletException
214: */
215: private function getPublicJwsKey() {
216: $publicKeyData = $this->getJwk($this->hyperwalletKeySetLocation, $this->signAlgorithm);
217: return new JWK($this->convertPrivateKeyToPublic($publicKeyData));
218: }
219:
220: /**
221: * Retrieves RSA private key by JWK key data
222: *
223: * @param array $privateKeyData The JWK key data
224: * @return RSA
225: */
226: /**
227: * Retrieves JWK key by JWK key set location and algorithm
228: *
229: * @param string $keySetLocation The location(URL or path to file) of JWK key set
230: * @param string $alg The target algorithm
231: * @return array
232: *
233: * @throws HyperwalletException
234: */
235: private function getJwk($keySetLocation, $alg) {
236: if (filter_var($keySetLocation, FILTER_VALIDATE_URL) === FALSE) {
237: if (!file_exists($keySetLocation)) {
238: throw new HyperwalletException("Wrong JWK key set location path = " . $keySetLocation);
239: }
240: }
241: return $this->findJwkByAlgorithm(json_decode(file_get_contents($keySetLocation), true), $alg);
242: }
243:
244: /**
245: * Retrieves JWK key from JWK key set by given algorithm
246: *
247: * @param string $jwkSetArray JWK key set
248: * @param string $alg The target algorithm
249: * @return array
250: *
251: * @throws HyperwalletException
252: */
253: private function findJwkByAlgorithm($jwkSetArray, $alg) {
254: foreach($jwkSetArray['keys'] as $jwk) {
255: if ($alg == $jwk['alg']) {
256: return $jwk;
257: }
258: }
259: throw new HyperwalletException("JWK set doesn't contain key with algorithm = " . $alg);
260: }
261:
262: /**
263: * Converts private key to public
264: *
265: * @param string $jwk JWK key
266: * @return array
267: */
268: private function convertPrivateKeyToPublic($jwk) {
269: if (isset($jwk['d'])) {
270: unset($jwk['d']);
271: }
272: if (isset($jwk['p'])) {
273: unset($jwk['p']);
274: }
275: if (isset($jwk['q'])) {
276: unset($jwk['q']);
277: }
278: if (isset($jwk['qi'])) {
279: unset($jwk['qi']);
280: }
281: if (isset($jwk['dp'])) {
282: unset($jwk['dp']);
283: }
284: if (isset($jwk['dq'])) {
285: unset($jwk['dq']);
286: }
287: return $jwk;
288: }
289:
290: /**
291: * Calculates JWS expiration time in seconds
292: *
293: * @return integer
294: */
295: private function getSignatureExpirationTime() {
296: date_default_timezone_set("UTC");
297: $secondsInMinute = 60;
298: return time() + $this->jwsExpirationMinutes * $secondsInMinute;
299: }
300:
301: /**
302: * Checks if header 'exp' param has not expired value
303: *
304: * @param array $header JWS header array
305: *
306: * @throws HyperwalletException
307: */
308: public function checkJwsExpiration($header) {
309: if(!isset($header['exp'])) {
310: throw new HyperwalletException('While trying to verify JWS signature no [exp] header is found');
311: }
312: $exp = $header['exp'];
313: if(!is_numeric($exp)) {
314: throw new HyperwalletException('Wrong value in [exp] header of JWS signature, must be integer');
315: }
316: if((int)time() > (int)$exp) {
317: throw new HyperwalletException('JWS signature has expired, checked by [exp] JWS header');
318: }
319: }
320:
321: /**
322: * Checks that the JWE header advertises the key-management algorithm and content-encryption method
323: * this client expects, before the header-controlled algorithm is ever used to decrypt with the
324: * private key. Prevents an attacker from forcing algorithm downgrade (e.g. to legacy RSA1_5) by
325: * tampering with the untrusted alg/enc header fields of an intercepted response.
326: *
327: * @param array $header JWE header array
328: *
329: * @throws HyperwalletException
330: */
331: public function checkJweHeaderAlgorithm($header) {
332: if (!isset($header['alg']) || $header['alg'] !== $this->encryptionAlgorithm) {
333: throw new HyperwalletException('While trying to decrypt JWE, unexpected [alg] header found');
334: }
335: if (!isset($header['enc']) || $header['enc'] !== $this->encryptionMethod) {
336: throw new HyperwalletException('While trying to decrypt JWE, unexpected [enc] header found');
337: }
338: }
339:
340: }
341: