4 * This file is part of the civicrm-cxn-rpc package.
6 * Copyright (c) CiviCRM LLC <info@civicrm.org>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this package.
12 namespace Civi\Cxn\Rpc\Message
;
14 use Civi\Cxn\Rpc\AesHelper
;
15 use Civi\Cxn\Rpc\Exception\InvalidMessageException
;
16 use Civi\Cxn\Rpc\Message
;
17 use Civi\Cxn\Rpc\CxnStore\CxnStoreInterface
;
18 use Civi\Cxn\Rpc\Constants
;
20 class StdMessage
extends Message
{
21 const NAME
= 'CXN-0.2-AES-CBC-HMAC';
27 * @param string $cxnId
28 * @param string $secret
29 * Base64-encoded secret.
33 public function __construct($cxnId, $secret, $data) {
34 parent
::__construct($data);
35 $this->cxnId
= $cxnId;
36 $this->secret
= $secret;
41 * @throws InvalidMessageException
43 public function encode() {
44 list($body, $signature) = AesHelper
::encryptThenSign($this->secret
, json_encode($this->data
));
45 return self
::NAME
// unsignable; determines decoder
46 . Constants
::PROTOCOL_DELIM
. $this->cxnId
// unsignable; determines key
47 . Constants
::PROTOCOL_DELIM
. $signature
48 . Constants
::PROTOCOL_DELIM
. $body;
52 * @param CxnStoreInterface $cxnStore
53 * A repository that contains shared secrets.
54 * @param string $message
57 * @throws InvalidMessageException
59 public static function decode($cxnStore, $message) {
60 list ($parsedProt, $parsedCxnId, $parsedHmac, $parsedBody) = explode(Constants
::PROTOCOL_DELIM
, $message, 4);
61 if ($parsedProt != self
::NAME
) {
62 throw new InvalidMessageException('Incorrect coding. Expected: ' . self
::NAME
);
64 $cxn = $cxnStore->getByCxnId($parsedCxnId);
66 throw new InvalidMessageException('Unknown connection ID');
69 $jsonPlaintext = AesHelper
::authenticateThenDecrypt($cxn['secret'], $parsedBody, $parsedHmac);
71 return new StdMessage($parsedCxnId, $cxn['secret'], json_decode($jsonPlaintext, TRUE));
77 public function getCxnId() {
82 * @param string $cxnId
84 public function setCxnId($cxnId) {
85 $this->cxnId
= $cxnId;
91 public function getSecret() {
96 * @param string $secret
98 public function setSecret($secret) {
99 $this->secret
= $secret;