Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP #84

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open

WIP #84

Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/run-tests.yml
Original file line number Diff line number Diff line change
@@ -18,7 +18,7 @@ jobs:
max-parallel: 1
fail-fast: true
matrix:
php: [7.4, 8.0, 8.1, 8.2]
php: [8.0, 8.1, 8.2]
env:
PUBLISH_KEY: ${{ secrets.PUBLISH_KEY }}
SUBSCRIBE_KEY: ${{ secrets.SUBSCRIBE_KEY }}
48 changes: 25 additions & 23 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -1,27 +1,29 @@
PubNub Real-time Cloud-Hosted Push API and Push Notification Client Frameworks
Copyright (c) 2013 PubNub Inc.
http://www.pubnub.com/
http://www.pubnub.com/terms
PubNub Software Development Kit License Agreement
Copyright © 2023 PubNub Inc. All rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
Subject to the terms and conditions of the license, you are hereby granted
a non-exclusive, worldwide, royalty-free license to (a) copy and modify
the software in source code or binary form for use with the software services
and interfaces provided by PubNub, and (b) redistribute unmodified copies
of the software to third parties. The software may not be incorporated in
or used to provide any product or service competitive with the products
and services of PubNub.

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
The above copyright notice and this license shall be included
in or with all copies or substantial portions of the software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
This license does not grant you permission to use the trade names, trademarks,
service marks, or product names of PubNub, except as required for reasonable
and customary use in describing the origin of the software and reproducing
the content of this license.

PubNub Real-time Cloud-Hosted Push API and Push Notification Client Frameworks
Copyright (c) 2013 PubNub Inc.
http://www.pubnub.com/
http://www.pubnub.com/terms
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
EVENT SHALL PUBNUB OR THE AUTHORS OR COPYRIGHT HOLDERS OF THE SOFTWARE BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

https://www.pubnub.com/
https://www.pubnub.com/terms
2 changes: 2 additions & 0 deletions examples/Time.php
Original file line number Diff line number Diff line change
@@ -3,10 +3,12 @@
require_once __DIR__ . '/../vendor/autoload.php';

use PubNub\Models\Consumer\PNTimeResult;
use PubNub\Crypto\Cryptor;

$pnconfig = \PubNub\PNConfiguration::demoKeys();
$pubnub = new \PubNub\PubNub($pnconfig);

$result = $pubnub->time()->sync();

printf("Server Time is: %s", date("Y-m-d H:i:s", $result->getTimetoken()));

62 changes: 62 additions & 0 deletions src/PubNub/Crypto/AesCbcCryptor.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<?php

namespace PubNub\Crypto;

use PubNub\Crypto\Payload as CryptoPayload;
use PubNub\Crypto\PaddingTrait;

class AesCbcCryptor extends Cryptor
{
use PaddingTrait;

public const CRYPTOR_ID = 'ACRH';
public const IV_LENGTH = 16;
public const BLOCK_SIZE = 16;
public const CIPHER_ALGO = 'aes-256-cbc';

protected string $cipherKey;

public function __construct(string $cipherKey)
{
$this->cipherKey = $cipherKey;
}

public function getIV(): string
{
return random_bytes(self::IV_LENGTH);
}

public function getCipherKey($cipherKey = null): string
{
return $cipherKey ? $cipherKey : $this->cipherKey;
}

protected function getSecret(string $cipherKey): string
{
$key = !is_null($cipherKey) ? $cipherKey : $this->cipherKey;
return hash("sha256", $key, true);
}

public function encrypt(string $text, ?string $cipherKey = null): CryptoPayload
{
$secret = $this->getSecret($this->getCipherKey($cipherKey));
$iv = $this->getIV();
$encrypted = openssl_encrypt($text, self::CIPHER_ALGO, $secret, OPENSSL_RAW_DATA, $iv);
return new CryptoPayload($encrypted, $iv, self::CRYPTOR_ID);
}

public function decrypt(CryptoPayload $payload, ?string $cipherKey = null)
{
$text = $payload->getData();
$secret = $this->getSecret($this->getCipherKey($cipherKey));
$iv = $payload->getCryptorData();
$decrypted = openssl_decrypt($text, self::CIPHER_ALGO, $secret, OPENSSL_RAW_DATA, $iv);
$result = json_decode($decrypted);

if ($result === null) {
return $decrypted;
} else {
return $result;
}
}
}
13 changes: 13 additions & 0 deletions src/PubNub/Crypto/Cryptor.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

namespace PubNub\Crypto;

use PubNub\Crypto\Payload as CryptoPayload;

abstract class Cryptor
{
public const CRYPTOR_ID = null;

abstract public function encrypt(string $text, ?string $cipherKey = null): CryptoPayload;
abstract public function decrypt(CryptoPayload $payload, ?string $cipherKey = null);
}
44 changes: 44 additions & 0 deletions src/PubNub/Crypto/Header.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

namespace PubNub\Crypto;

class Header
{
public const HEADER_VERSION = 1;
private string $sentinel;
private string $cryptorId;
private string $cryptorData;
private int $length;

public function __construct(
string $sentinel,
string $cryptorId,
string $cryptorData,
int $length
) {
$this->sentinel = $sentinel;
$this->cryptorId = $cryptorId;
$this->cryptorData = $cryptorData;
$this->length = $length;
}

public function getSentinel(): string
{
return $this->sentinel;
}

public function getCryptorId(): string
{
return $this->cryptorId;
}

public function getCryptorData(): string
{
return $this->cryptorData;
}

public function getLength(): int
{
return $this->length;
}
}
101 changes: 101 additions & 0 deletions src/PubNub/Crypto/LegacyCryptor.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
<?php

namespace PubNub\Crypto;

use PubNub\Crypto\Cryptor;
use PubNub\Exceptions\PubNubResponseParsingException;
use PubNub\Crypto\PaddingTrait;

class LegacyCryptor extends Cryptor
{
use PaddingTrait;

public const CRYPTOR_ID = '0000';
public const IV_LENGTH = 16;
public const BLOCK_SIZE = 16;
public const CIPHER_ALGO = 'aes-256-cbc';
protected const STATIC_IV = '0123456789012345';

protected string $cipherKey;
protected bool $useRandomIV;

public function __construct(string $key, bool $useRandomIV)
{
$this->cipherKey = $key;
$this->useRandomIV = $useRandomIV;
}

public function getIV(): string
{
if (!$this->useRandomIV) {
return self::STATIC_IV;
}
return random_bytes(static::IV_LENGTH);
}

public function getCipherKey(): string
{
return $this->cipherKey;
}

public function encrypt(string $text, ?string $cipherKey = null): Payload
{
$iv = $this->getIV();
$shaCipherKey = substr(hash("sha256", $this->cipherKey), 0, 32);
$padded = $this->pad($text, self::BLOCK_SIZE);
$encrypted = openssl_encrypt($text, self::CIPHER_ALGO, $shaCipherKey, OPENSSL_RAW_DATA, $iv);
if ($this->useRandomIV) {
$encryptedWithIV = $iv . $encrypted;
} else {
$encryptedWithIV = $encrypted;
}
return new Payload($encryptedWithIV, '', self::CRYPTOR_ID);
}

public function decrypt(Payload $payload, ?string $cipherKey = null)
{
$text = $payload->getData();
if (strlen($text) === 0) {
throw new PubNubResponseParsingException("Decryption error: message is empty");
}

if (is_array($text)) {
if (array_key_exists("pn_other", $text)) {
$text = $text["pn_other"];
} else {
if (is_array($text)) {
throw new PubNubResponseParsingException("Decryption error: message is not a string");
} else {
throw new PubNubResponseParsingException("Decryption error: pn_other object key missing");
}
}
} elseif (!is_string($text)) {
throw new PubNubResponseParsingException("Decryption error: message is not a string or object");
}

$shaCipherKey = substr(hash("sha256", $this->cipherKey), 0, 32);

if ($this->useRandomIV) {
$iv = substr($text, 0, 16);
$data = substr($text, 16);
} else {
$iv = self::STATIC_IV;
$data = $text;
}
$decrypted = openssl_decrypt($data, 'aes-256-cbc', $shaCipherKey, OPENSSL_RAW_DATA, $iv);

if ($decrypted === false) {
throw new PubNubResponseParsingException("Decryption error: " . openssl_error_string());
}

$unPadded = $this->depad($decrypted, self::BLOCK_SIZE);

$result = json_decode($unPadded);

if ($result === null) {
return $unPadded;
} else {
return $result;
}
}
}
46 changes: 46 additions & 0 deletions src/PubNub/Crypto/PaddingTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php

namespace PubNub\Crypto;

trait PaddingTrait
{
/**
* Pad $text to multiple of $blockSize lenght using PKCS5Padding schema
*
* @param string $text
* @param int $blockSize
* @return string
*/
public function pad(string $text, int $blockSize)
{
$pad = $blockSize - (strlen($text) % $blockSize);
return $text . str_repeat(chr($pad), $pad);
}

/**
* Remove padding from $text using PKCS5Padding schema
*
* @param string $text
* @param int $blockSize
* @return string
*/
public function depad($data, $blockSize)
{
$length = strlen($data);
if ($length == 0) {
return $data;
}

$padLength = substr($data, -1);

if (ord($padLength) <= $blockSize) {
for ($i = $length - 2; $i > 0; $i--) {
if (ord($data [$i] != $padLength)) {
break;
}
}
return substr($data, 0, $i + 1);
}
return $data;
}
}
32 changes: 32 additions & 0 deletions src/PubNub/Crypto/Payload.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

namespace PubNub\Crypto;

class Payload
{
private string $data;
private ?string $cryptorData;
private ?string $cryptorId;

public function __construct(string $data, ?string $cryptorData = null, ?string $cryptorId = null)
{
$this->data = $data;
$this->cryptorData = $cryptorData;
$this->cryptorId = $cryptorId;
}

public function getData(): string
{
return $this->data;
}

public function getCryptorData(): ?string
{
return $this->cryptorData;
}

public function getCryptorId(): ?string
{
return $this->cryptorId;
}
}
182 changes: 182 additions & 0 deletions src/PubNub/CryptoModule.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
<?php

namespace PubNub;

use PubNub\Crypto\AesCbcCryptor;
use PubNub\Crypto\Cryptor;
use PubNub\Crypto\Header as CryptoHeader;
use PubNub\Crypto\LegacyCryptor;
use PubNub\Crypto\Payload as CryptoPayload;
use PubNub\Exceptions\PubNubCryptoException;
use PubNub\Exceptions\PubNubResponseParsingException;

class CryptoModule
{
public const CRYPTOR_VERSION = 1;
public const FALLBACK_CRYPTOR_ID = '0000';
protected const SENTINEL = 'PNED';

private $cryptorMap = [];
private string $defaultCryptorId;

public function __construct($cryptorMap, string $defaultCryptorId)
{
$this->cryptorMap = $cryptorMap;
$this->defaultCryptorId = $defaultCryptorId;
}

public function registerCryptor(Cryptor $cryptor, ?string $cryptorId = null): self
{
if (is_null($cryptorId)) {
$cryptorId = $cryptor::CRYPTOR_ID;
}

if (strlen($cryptorId) != 4) {
throw new PubNubCryptoException('Malformed cryptor id');
}

if (key_exists($cryptorId, $this->cryptorMap)) {
throw new PubNubCryptoException('Cryptor id already in use');
}

if (!$cryptor instanceof Cryptor) {
throw new PubNubCryptoException('Invalid Cryptor instance');
}

$this->cryptorMap[$cryptorId] = $cryptor;

return $this;
}

protected function stringify($data): string
{
if (is_string($data)) {
return $data;
} else {
return json_encode($data);
}
}

public function encrypt($data, ?string $cryptorId = null): string
{
if (($data) == '') {
throw new PubNubResponseParsingException("Encryption error: message is empty");
}
$cryptorId = is_null($cryptorId) ? $this->defaultCryptorId : $cryptorId;
$cryptor = $this->cryptorMap[$cryptorId];
$text = $this->stringify($data);
$cryptoPayload = $cryptor->encrypt($text);
$header = $this->encodeHeader($cryptoPayload);
return base64_encode($header . $cryptoPayload->getData());
}

public function decrypt(string | object $input): string | object
{
$input = $this->parseInput($input);
$data = base64_decode($input);
$header = $this->decodeHeader($data);

if (!$this->cryptorMap[$header->getCryptorId()]) {
throw new PubNubCryptoException('unknown cryptor error');
}
$payload = new CryptoPayload(
substr($data, $header->getLength()),
$header->getCryptorData(),
$header->getCryptorId(),
);

return $this->cryptorMap[$header->getCryptorId()]->decrypt($payload);
}

public function encodeHeader(CryptoPayload $payload): string
{
if ($payload->getCryptorId() == self::FALLBACK_CRYPTOR_ID) {
return '';
}

$version = chr(CryptoHeader::HEADER_VERSION);

$crdLen = strlen($payload->getCryptorData());
if ($crdLen > 65535) {
throw new PubNubCryptoException('Cryptor data is too long');
}

if ($crdLen < 255) {
$cryptorDataLength = chr($crdLen);
} else {
$hexlen = str_split(str_pad(dechex($crdLen), 4, 0, STR_PAD_LEFT), 2);
$cryptorDataLength = chr(255) . chr(hexdec($hexlen[0])) . chr(hexdec($hexlen[1]));
}

return self::SENTINEL . $version . $payload->getCryptorId() . $cryptorDataLength . $payload->getCryptorData();
}

public function decodeHeader(string $header): CryptoHeader
{
if (strlen($header < 10) or substr($header, 0, 4) != self::SENTINEL) {
return new CryptoHeader('', self::FALLBACK_CRYPTOR_ID, '', 0);
}
$sentinel = substr($header, 0, 4);
$version = ord($header[4]);
if ($version > CryptoHeader::HEADER_VERSION) {
throw new PubNubCryptoException('unknown cryptor error');
}
$cryptorId = substr($header, 5, 4);
$cryptorDataLength = ord($header[9]);
if ($cryptorDataLength < 255) {
$cryptorData = substr($header, 10, $cryptorDataLength);
$headerLength = 10 + $cryptorDataLength;
} else {
$cryptorDataLength = ord($header[10]) * 256 + ord($header[11]);
$cryptorData = substr($header, 12, $cryptorDataLength);
$headerLength = 12 + $cryptorDataLength;
}
return new CryptoHeader($sentinel, $cryptorId, $cryptorData, $headerLength);
}

public static function legacyCryptor(string $cipherKey, bool $useRandomIV): self
{
return new self(
[
LegacyCryptor::CRYPTOR_ID => new LegacyCryptor($cipherKey, $useRandomIV),
AesCbcCryptor::CRYPTOR_ID => new AesCbcCryptor($cipherKey),
],
LegacyCryptor::CRYPTOR_ID
);
}

public static function aesCbcCryptor(string $cipherKey, bool $useRandomIV): self
{
return new self(
[
LegacyCryptor::CRYPTOR_ID => new LegacyCryptor($cipherKey, $useRandomIV),
AesCbcCryptor::CRYPTOR_ID => new AesCbcCryptor($cipherKey),
],
aesCbcCryptor::CRYPTOR_ID
);
}

// for backward compatibility
public function getCipherKey()
{
return $this->cryptorMap[$this->defaultCryptorId]->getCipherKey();
}

public function parseInput(string | object $input): string
{
if (is_array($input)) {
if (array_key_exists("pn_other", $input)) {
$input = $input["pn_other"];
} else {
throw new PubNubResponseParsingException("Decryption error: pn_other object key missing");
}
} elseif (!is_string($input)) {
throw new PubNubResponseParsingException("Decryption error: message is not a string or object");
}

if (strlen($input) == '') {
throw new PubNubResponseParsingException("Decryption error: message is empty");
}
return $input;
}
}
29 changes: 29 additions & 0 deletions src/PubNub/Exceptions/PubNubCryptoException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

namespace PubNub\Exceptions;

class PubNubCryptoException extends PubNubException
{
/** @var \Exception */
protected $originalException;

/**
* @return \Exception
*/
public function getOriginalException()
{
return $this->originalException;
}

/**
* @param \Exception $originalException
* @return $this
*/
public function setOriginalException($originalException)
{
$this->originalException = $originalException;
$this->message = $originalException->getMessage();

return $this;
}
}
10 changes: 8 additions & 2 deletions src/PubNub/Models/Consumer/History/PNHistoryItemResult.php
Original file line number Diff line number Diff line change
@@ -2,9 +2,9 @@

namespace PubNub\Models\Consumer\History;

use PubNub\Exceptions\PubNubResponseParsingException;
use PubNub\PubNubCryptoCore;


class PNHistoryItemResult
{
/** @var any */
@@ -36,7 +36,13 @@ public function __toString()

public function decrypt()
{
$this->entry = $this->crypto->decrypt($this->entry);
if (is_string($this->entry)) {
$this->entry = $this->crypto->decrypt($this->entry);
} elseif (is_array($this->entry) and key_exists('pn_other', $this->entry)) {
$this->entry = $this->crypto->decrypt($this->entry['pn_other']);
} else {
throw new PubNubResponseParsingException("Decryption error: message is not a string");
}
}

/**
3 changes: 2 additions & 1 deletion src/PubNub/PNConfiguration.php
Original file line number Diff line number Diff line change
@@ -5,6 +5,7 @@
use PubNub\Exceptions\PubNubConfigurationException;
use PubNub\Exceptions\PubNubValidationException;
use WpOrg\Requests\Transport;
use PubNub\CryptoModule;

class PNConfiguration
{
@@ -136,7 +137,7 @@ public function isAesEnabled()
public function setCipherKey($cipherKey)
{
if ($this->crypto == null) {
$this->crypto = new PubNubCrypto($cipherKey, $this->getUseRandomIV());
$this->crypto = CryptoModule::legacyCryptor($cipherKey, $this->getUseRandomIV());
} else {
$this->getCrypto()->setCipherKey($cipherKey);
}
File renamed without changes.
132 changes: 132 additions & 0 deletions tests/unit/CryptoModule/CryptoModuleTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
<?php

namespace PubNubTests\unit\CryptoModule;

use Generator;
use PHPUnit\Framework\TestCase;
use PubNub\CryptoModule;
use PubNub\Exceptions\PubNubResponseParsingException;

class CryptoModuleTest extends TestCase
{
protected string $cipherKey = "myCipherKey";

/**
* @dataProvider decodeProvider
* @param string $encrypted
* @param mixed $expected
* @return void
*/
public function testDecode(CryptoModule $module, string $encrypted, mixed $expected): void
{
try {
$decrypted = $module->decrypt($encrypted);
} catch (PubNubResponseParsingException $e) {
$decrypted = $e->getMessage();
}
$this->assertEquals($expected, $decrypted);
}

/**
* @dataProvider encodeProvider
* @param string $message
* @param mixed $expected
* @return void
*/
public function testEnode(CryptoModule $module, string $message, mixed $expected): void
{
try {
$encrypted = $module->encrypt($message);
if (!$expected) {
$this->assertEquals($message, $module->decrypt($encrypted));
return;
}
} catch (PubNubResponseParsingException $e) {
$encrypted = $e->getMessage();
}
$this->assertEquals($expected, $encrypted);
}

protected function encodeProvider(): Generator
{
$legacyRandomModule = CryptoModule::legacyCryptor($this->cipherKey, true);
$legacyStaticModule = CryptoModule::legacyCryptor($this->cipherKey, false);
$aesCbcModuleStatic = CryptoModule::aesCbcCryptor($this->cipherKey, false);
$aesCbcModuleRandom = CryptoModule::aesCbcCryptor($this->cipherKey, true);

yield [$legacyRandomModule, '', 'Encryption error: message is empty'];
yield [$legacyStaticModule, '', 'Encryption error: message is empty'];
yield [$aesCbcModuleStatic, '', 'Encryption error: message is empty'];
yield [
$legacyStaticModule,
"Hello world encrypted with legacyModuleStaticIv",
"OtYBNABjeAZ9X4A91FQLFBo4th8et/pIAsiafUSw2+L8iWqJlte8x/eCL5cyjzQa",
];
yield [
$legacyRandomModule,
"Hello world encrypted with legacyModuleRandomIv",
null,
];
yield [
$legacyStaticModule,
"Hello world encrypted with legacyModuleStaticIv",
null,
];
// test fallback decrypt with static IV
yield [
$aesCbcModuleStatic,
"Hello world encrypted with legacyModuleStaticIv",
null,
];
// test falback decrypt with random IV
yield [
$aesCbcModuleRandom,
"Hello world encrypted with legacyModuleRandomIv",
null,
];
yield [
$aesCbcModuleRandom,
'Hello world encrypted with aesCbcModule',
null,
];
}

protected function decodeProvider(): Generator
{
$legacyRandomModule = CryptoModule::legacyCryptor($this->cipherKey, true);
$legacyStaticModule = CryptoModule::legacyCryptor($this->cipherKey, false);
$aesCbcModuleStatic = CryptoModule::aesCbcCryptor($this->cipherKey, false);
$aesCbcModuleRandom = CryptoModule::aesCbcCryptor($this->cipherKey, true);

yield [$legacyRandomModule, '', 'Decryption error: message is empty'];
yield [$legacyStaticModule, '', 'Decryption error: message is empty'];
yield [$aesCbcModuleStatic, '', 'Decryption error: message is empty'];
yield [
$legacyRandomModule,
"T3J9iXI87PG9YY/lhuwmGRZsJgA5y8sFLtUpdFmNgrU1IAitgAkVok6YP7lacBiVhBJSJw39lXCHOLxl2d98Bg==",
"Hello world encrypted with legacyModuleRandomIv",
];
yield [
$legacyStaticModule,
"OtYBNABjeAZ9X4A91FQLFBo4th8et/pIAsiafUSw2+L8iWqJlte8x/eCL5cyjzQa",
"Hello world encrypted with legacyModuleStaticIv",
];
// test fallback decrypt with static IV
yield [
$aesCbcModuleStatic,
"OtYBNABjeAZ9X4A91FQLFBo4th8et/pIAsiafUSw2+L8iWqJlte8x/eCL5cyjzQa",
"Hello world encrypted with legacyModuleStaticIv",
];
// test falback decrypt with random IV
yield [
$aesCbcModuleRandom,
"T3J9iXI87PG9YY/lhuwmGRZsJgA5y8sFLtUpdFmNgrU1IAitgAkVok6YP7lacBiVhBJSJw39lXCHOLxl2d98Bg==",
"Hello world encrypted with legacyModuleRandomIv",
];
yield [
$aesCbcModuleRandom,
'UE5FRAFBQ1JIEKzlyoyC/jB1hrjCPY7zm+X2f7skPd0LBocV74cRYdrkRQ2BPKeA22gX/98pMqvcZtFB6TCGp3Zf1M8F730nlfk=',
'Hello world encrypted with aesCbcModule',
];
}
}
116 changes: 116 additions & 0 deletions tests/unit/CryptoModule/HeaderEncoderTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
<?php

namespace PubNubTests\unit\CryptoModule;

use Generator;
use PHPUnit\Framework\TestCase;
use PubNub\CryptoModule;
use PubNub\Crypto\Header as CryptoHeader;
use PubNub\Crypto\Payload as CryptoPayload;
use PubNub\Crypto\AesCbcCryptor;

class HeaderEncoderTest extends TestCase
{
protected CryptoModule $module;

protected function setUp(): void
{
$this->module = new CryptoModule([], "0000");
}

/**
* @dataProvider provideDecodeHeader
* @param string $header
* @param CryptoHeader $expected
* @return void
*/
public function testDecodeHeader(string $header, CryptoHeader $expected): void
{
$decoded = $this->module->decodeHeader($header);
$this->assertEquals($expected, $decoded);
}

/**
* @dataProvider provideEncodeHeader
*
* @param CryptoHeader $expected
* @param string $
* @return void
*/
public function testEncodeHeader(CryptoPayload $payload, string $expected): void
{
$encoded = $this->module->encodeHeader($payload);
$this->assertEquals($expected, $encoded);
}

public function provideDecodeHeader(): Generator
{
// decoding empty string should point to fallback cryptor
yield ["", new CryptoHeader("", CryptoModule::FALLBACK_CRYPTOR_ID, "", 0)];

// decoding header without cryptor data
yield ["PNED\x01ACRH\x00", new CryptoHeader("PNED", "ACRH", "", 10)];

// decoding with any data should add data length segment
$cryptorData = "\x20";
yield [
"PNED\x01ACRH\x01" . $cryptorData,
new CryptoHeader("PNED", "ACRH", $cryptorData, 10 + strlen($cryptorData))
];

// if cryptor data is less than 255 characters data length segment is 1 byte long
$cryptorData = str_repeat("\x20", 254);
yield [
"PNED\x01ACRH\xfe" . $cryptorData,
new CryptoHeader("PNED", "ACRH", $cryptorData, 10 + strlen($cryptorData))
];

// if cryptor data is greater than or equal 255 characters data length segment is 3 bytes long
$cryptorData = str_repeat("\x20", 255);
yield [
"PNED\x01ACRH\xff\x00\xff" . $cryptorData,
new CryptoHeader("PNED", "ACRH", $cryptorData, 12 + strlen($cryptorData))
];

$cryptorData = str_repeat("\x20", 65535);
yield [
"PNED\x01ACRH\xff\xff\xff" . $cryptorData,
new CryptoHeader("PNED", "ACRH", $cryptorData, 12 + strlen($cryptorData))
];
}

public function provideEncodeHeader(): Generator
{
$message = "";
$cryptorData = "";
// encode empty header for fallback cryptor
yield [new CryptoPayload($message, $cryptorData, CryptoModule::FALLBACK_CRYPTOR_ID), ""];

// encode header without cryptor data
yield [new CryptoPayload($message, $cryptorData, AesCbcCryptor::CRYPTOR_ID), "PNED\x01ACRH\x00"];

// header with cryptor data should include length byte
$cryptorData = "\x20";
yield [
new CryptoPayload($message, $cryptorData, AesCbcCryptor::CRYPTOR_ID),
"PNED\x01ACRH\x01" . $cryptorData,
];
$cryptorData = str_repeat("\x20", 254);
yield [
new CryptoPayload($message, $cryptorData, AesCbcCryptor::CRYPTOR_ID),
"PNED\x01ACRH\xfe" . $cryptorData,
];

// encoding header with cryptor data longer than 254 bytes should include three length bytes
$cryptorData = str_repeat("\x20", 255);
yield [
new CryptoPayload($message, $cryptorData, AesCbcCryptor::CRYPTOR_ID),
"PNED\x01ACRH\xff\x00\xff" . $cryptorData,
];
$cryptorData = str_repeat("\x20", 65535);
yield [
new CryptoPayload($message, $cryptorData, AesCbcCryptor::CRYPTOR_ID),
"PNED\x01ACRH\xff\xff\xff" . $cryptorData,
];
}
}
59 changes: 59 additions & 0 deletions tests/unit/CryptoModule/PaddingTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<?php

namespace PubNubTests\unit\CryptoModule;

use Generator;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\TestCase;
use PubNub\Crypto\LegacyCryptor;
use SebastianBergmann\RecursionContext\InvalidArgumentException;

class PaddingTest extends TestCase
{
protected LegacyCryptor $cryptor;
protected function setUp(): void
{
$this->cryptor = new LegacyCryptor("myCipherKey", false);
}

/**
* @dataProvider padProvider
* @param string $plain
* @param string $padded
* @return void
* @throws InvalidArgumentException
* @throws ExpectationFailedException
*/
public function testPad(string $plain, string $padded): void
{
$this->assertEquals($this->cryptor->pad($plain), $padded);
}

/**
* @dataProvider depadProvider
* @param string $padded
* @param string $expected
* @return void
* @throws InvalidArgumentException
* @throws ExpectationFailedException
*/
public function testDepad(string $padded, string $expected): void
{
$this->assertEquals($this->cryptor->depad($padded), $expected);
}

public function padProvider(): Generator
{
yield ["123456789012345", "123456789012345\x01"];
yield ["12345678901234", "12345678901234\x02\x02"];
yield ["1234567890123456", "1234567890123456" . str_repeat("\x10", 16)];
}

public function depadProvider(): Generator
{
yield ["123456789012345\x01", "123456789012345"];
yield ["12345678901234\x02\x02", "12345678901234"];
yield ["1234567890123456" . str_repeat("\x10", 16), "1234567890123456"];
yield ["1234567890123456", "1234567890123456"];
}
}