Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
abmmhasan committed Jan 29, 2024
1 parent c63497f commit a659264
Show file tree
Hide file tree
Showing 22 changed files with 153 additions and 85 deletions.
11 changes: 7 additions & 4 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,16 +27,19 @@ jobs:
tools: composer:v2
coverage: xdebug

- name: Validate composer.json and composer.lock
- name: Check PHP Version
run: php -v

- name: Validate Composer
run: composer validate --strict

- name: Install dependencies
run: composer install --no-interaction --prefer-dist --optimize-autoloader

- name: Check PHP Version
run: php -v
- name: Auditing packages
run: composer audit

- name: Pest Tests
- name: Test
run: ./vendor/bin/pest
#
# - name: Rector(Dry) Tests
Expand Down
8 changes: 3 additions & 5 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,19 +25,17 @@
"minimum-stability": "dev",
"prefer-stable": true,
"require": {
"php": ">=8.0"
},
"suggest": {
"php": ">=8.2",
"ext-json": "*",
"ext-openssl": "*",
"ext-mbstring": "*",
"ext-ctype": "*",
"ext-sodium": "*"
},
"require-dev": {
"pestphp/pest": "^2.9",
"pestphp/pest": "^2.24",
"symfony/var-dumper": "^6.3",
"rector/rector": "^0.17.6"
"rector/rector": "^0.18"
},
"config": {
"optimize-autoloader": true,
Expand Down
3 changes: 2 additions & 1 deletion phpunit.xml
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.2/phpunit.xsd" bootstrap="vendor/autoload.php"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.2/phpunit.xsd"
bootstrap="vendor/autoload.php"
colors="true">
<testsuites>
<testsuite name="Test Suite">
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?php

namespace AbmmHasan\SafeGuard\Asymmetric;
namespace AbmmHasan\SafeGuard\Asymmetric\OpenSSL;

use Exception;

Expand Down
22 changes: 22 additions & 0 deletions src/Asymmetric/OpenSSL/DiffieHellman.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
namespace AbmmHasan\SafeGuard\Asymmetric\OpenSSL;


use Exception;
use OpenSSLAsymmetricKey;

class DiffieHellman
Expand Down Expand Up @@ -60,4 +61,25 @@ public function computeSecretKey(string $publicKey, bool $encoded = true): bool|
}
return openssl_dh_compute_key($publicKey, $this->resource);
}

/**
* Generate a prime number
*
* @param int $privateKeyBitSize
* @return string
* @throws Exception
*/
public static function getPrime(int $privateKeyBitSize = 2048): string
{
if ($privateKeyBitSize < 384) {
throw new Exception('Invalid private key bit size! Should be at-least 384.');
}

return openssl_pkey_get_details(
openssl_pkey_new([
'private_key_bits' => $privateKeyBitSize,
'private_key_type' => OPENSSL_KEYTYPE_DH
])
)['dh']['p'];
}
}
34 changes: 24 additions & 10 deletions src/Asymmetric/OpenSSL/OpenSSLKeygen.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,60 +66,68 @@ public function __construct(
*
* @param $key
* @param $value
* @return OpenSSLKeygen
* @throws Exception
*/
public function setCsrOptions($key, $value)
public function setCsrOptions($key, $value): OpenSSLKeygen
{
if ($key === 'config') {
$this->setConfPath($value);
} else {
$this->csrOption[$key] = $value;
}
return $this;
}

/**
* Set options for keys
*
* @param $key
* @param $value
* @return OpenSSLKeygen
* @throws Exception
*/
public function setKeyOptions($key, $value)
public function setKeyOptions($key, $value): OpenSSLKeygen
{
if ($key === 'config') {
$this->setConfPath($value);
} else {
$this->keyOption[$key] = $value;
}
return $this;
}

/**
* Set openssl.conf file path
*
* @param string $path
* @return OpenSSLKeygen
* @throws Exception
*/
public function setConfPath(string $path)
public function setConfPath(string $path): OpenSSLKeygen
{
$path = realpath($path);
if (empty($path)) {
throw new Exception('Invalid openssl.conf file path!');
}
$this->csrOption['config'] = $this->keyOption['config'] = $path;
return $this;
}

/**
* Set predefined pkey resource
*
* @param string|null $keyPair
* @param string|null $csrResource
* @return OpenSSLKeygen
*/
public function setResource(string $keyPair = null, string $csrResource = null)
public function setResource(string $keyPair = null, string $csrResource = null): OpenSSLKeygen
{
$this->resource = [
'keyPair' => $keyPair,
'csr' => $csrResource,
];
return $this;
}

/**
Expand Down Expand Up @@ -186,16 +194,18 @@ public function export(string $path, string $name = 'server'): bool
* @param int $daysValidFor
* @param string|null $passphrase
* @param string|null $certificate
* @return OpenSSLKeygen
* @throws Exception
*/
public function dsa(int $daysValidFor = 365, string $passphrase = null, string $certificate = null)
public function dsa(int $daysValidFor = 365, string $passphrase = null, string $certificate = null): OpenSSLKeygen
{
$this->csrOption['private_key_type'] = $this->keyOption['private_key_type'] = OPENSSL_KEYTYPE_DSA;
$this->csrOption['digest_alg'] ??= 'DSA';
$this->certificate['type'] = 'dsa';
$this->generateKeyResource($passphrase);
$this->generateCsr();
$this->generateSigned($daysValidFor, $certificate);
return $this;
}

/**
Expand All @@ -204,16 +214,18 @@ public function dsa(int $daysValidFor = 365, string $passphrase = null, string $
* @param int $daysValidFor
* @param null|string $passphrase
* @param null|string $certificate
* @return OpenSSLKeygen
* @throws Exception
*/
public function rsa(int $daysValidFor = 365, string $passphrase = null, string $certificate = null)
public function rsa(int $daysValidFor = 365, string $passphrase = null, string $certificate = null): OpenSSLKeygen
{
$this->csrOption['private_key_type'] = $this->keyOption['private_key_type'] = OPENSSL_KEYTYPE_RSA;
$this->csrOption['digest_alg'] ??= 'SHA512';
$this->certificate['type'] = 'rsa';
$this->generateKeyResource($passphrase);
$this->generateCsr();
$this->generateSigned($daysValidFor, $certificate);
return $this;
}

/**
Expand All @@ -222,23 +234,25 @@ public function rsa(int $daysValidFor = 365, string $passphrase = null, string $
* @param int $daysValidFor
* @param null|string $passphrase
* @param null|string $certificate
* @return OpenSSLKeygen
* @throws Exception
*/
public function ec(int $daysValidFor = 365, string $passphrase = null, string $certificate = null)
public function ec(int $daysValidFor = 365, string $passphrase = null, string $certificate = null): OpenSSLKeygen
{
$this->csrOption['private_key_type'] = $this->keyOption['private_key_type'] = OPENSSL_KEYTYPE_EC;
$this->csrOption['digest_alg'] ??= 'SHA512';
$this->certificate['type'] = 'ec';
$this->generateKeyResource($passphrase);
$this->generateCsr();
$this->generateSigned($daysValidFor, $certificate);
return $this;
}

/**
* @param $passphrase
* @throws Exception
*/
private function generateKeyResource($passphrase)
private function generateKeyResource($passphrase): void
{
if (empty(getenv('OPENSSL_CONF')) && (empty($this->csrOption['config']) || empty($this->keyOption['config']))) {
throw new Exception('openssl.conf file not found!');
Expand All @@ -256,7 +270,7 @@ private function generateKeyResource($passphrase)
openssl_pkey_export($this->resource['keyPair'], $this->certificate['private'], $passphrase, $this->keyOption);
}

private function generateCsr()
private function generateCsr(): void
{
if (empty($this->resource['csr'])) {
// Generate a Certificate Signing Request
Expand All @@ -267,7 +281,7 @@ private function generateCsr()
openssl_csr_export($this->resource['csr'], $this->certificate['csr']);
}

private function generateSigned($validFor, $certificate)
private function generateSigned($validFor, $certificate): void
{
// Export (Signed for given days) Certificate
openssl_x509_export(
Expand Down
1 change: 0 additions & 1 deletion src/Asymmetric/OpenSSL/RSA.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
namespace AbmmHasan\SafeGuard\Asymmetric\OpenSSL;


use AbmmHasan\SafeGuard\Asymmetric\Common;
use Exception;
use OpenSSLAsymmetricKey;
use OpenSSLCertificate;
Expand Down
3 changes: 2 additions & 1 deletion src/Asymmetric/Signature.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
namespace AbmmHasan\SafeGuard\Asymmetric;


use AbmmHasan\SafeGuard\Asymmetric\OpenSSL\Common;
use Exception;
use OpenSSLAsymmetricKey;
use OpenSSLCertificate;
Expand Down Expand Up @@ -34,7 +35,7 @@ public function __construct(
* @return string Signature
* @throws Exception|SodiumException
*/
public function Sign(
public function sign(
string $data,
OpenSSLAsymmetricKey|array|string|OpenSSLCertificate $key,
string $passphrase = null
Expand Down
4 changes: 2 additions & 2 deletions src/Hash/FileHash.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public function generate(string $filePath, string $secret = ''): bool|string
return match ($this->algorithm) {
'blake2b' => sodium_bin2hex($this->chunkedGenericHash($filePath, $secret)),
default => match (true) {
empty($this->secret) => hash_file($this->algorithm, $filePath),
empty($secret) => hash_file($this->algorithm, $filePath),
default => hash_hmac_file($this->algorithm, $filePath, $secret)
}
};
Expand All @@ -53,4 +53,4 @@ private function chunkedGenericHash(string $filePath, string $secret): string
}
return sodium_crypto_generichash_final($context, $this->hashLength);
}
}
}
2 changes: 1 addition & 1 deletion src/JWT/Asymmetric.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ public function encode(object|array|string $payload, mixed $keyId = null, array|
[$header, $payload] = $this->encodeHeaderNPayload($payload, $header, $keyId);

$signature = (new Signature(true, $this->algorithm))
->Sign($header . "." . $payload, $this->secret, $this->passphrase);
->sign($header . "." . $payload, $this->secret, $this->passphrase);

if (str_starts_with($this->algorithmTitle, 'ES')) {
$signature = (new MBStringConverter())->fromAsn1($signature, $this->keyLength[$this->algorithmTitle]);
Expand Down
8 changes: 4 additions & 4 deletions src/Misc/ReadFile.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@
/**
* Memory-safe file reader
*
* @method ReadFile character() Get character iterator
* @method ReadFile line() Get line iterator
* @method ReadFile csv(string $separator = ",", string $enclosure = "\"", string $escape = "\\") Get line iterator parsed as CSV
* @method ReadFile binary(int $bytes = 1024) Get binary iterator
* @method ReadFile character() Character iterator
* @method ReadFile line() Line iterator
* @method ReadFile csv(string $separator = ",", string $enclosure = "\"", string $escape = "\\") CSV iterator
* @method ReadFile binary(int $bytes = 1024) Binary iterator
*/
final class ReadFile
{
Expand Down
2 changes: 1 addition & 1 deletion src/Misc/SodiumKeygen.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ public static function sign(string $seed = null): object
public static function box(string $seed = null): object
{
if (!is_null($seed)) {
if ($length = strlen($seed) !== 32) {
if (($length = strlen($seed)) !== 32) {
throw new Exception("Invalid Seed size (Expected: 32B, Found: {$length}B)!");
}
$keypair = sodium_crypto_box_seed_keypair($seed);
Expand Down
3 changes: 2 additions & 1 deletion src/Symmetric/OpenSSL/FileCrypt.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,8 @@ public function encrypt(string $input, int $blockSize = 1024): string
}
$inputLocDetails = pathinfo($input);
if (empty($this->outFilePath)) {
$this->outFilePath = $inputLocDetails['dirname'] . DIRECTORY_SEPARATOR . $inputLocDetails['filename'] . '.bin';
$this->outFilePath = $inputLocDetails['dirname'] . DIRECTORY_SEPARATOR .
$inputLocDetails['filename'] . '.bin';
} else {
$outFile = pathinfo($this->outFilePath);
$this->outFilePath = ($outFile['dirname'] ?? $inputLocDetails['dirname']) .
Expand Down
10 changes: 6 additions & 4 deletions src/Symmetric/OpenSSL/SSLCommon.php
Original file line number Diff line number Diff line change
Expand Up @@ -182,8 +182,8 @@ private function calculateIV()
*/
private function encryptionProcess(string $input): string
{
self::calculateIV();
$encryptionKey = self::getKey();
$this->calculateIV();
$encryptionKey = $this->getKey();
$cText = openssl_encrypt(
$input,
$this->setInfo('encryptionMethod', $this->encryptionMethod),
Expand All @@ -193,7 +193,9 @@ private function encryptionProcess(string $input): string
$generatedTag,
$this->aad
);
$this->info['tag'][] = sodium_bin2base64($generatedTag, SODIUM_BASE64_VARIANT_ORIGINAL_NO_PADDING);
if ($generatedTag) {
$this->info['tag'][] = sodium_bin2base64($generatedTag, SODIUM_BASE64_VARIANT_ORIGINAL_NO_PADDING);
}
if ($this->setInfo('enableSignature', $this->enableSignature) === true) {
$cText = hash_hmac(
$this->setInfo('hmacAlgo', $this->hmacAlgo),
Expand All @@ -219,7 +221,7 @@ private function decryptionProcess(string $input): bool|string
{
$ivLen = openssl_cipher_iv_length($this->encryptionMethod);
$cTextOffset = 0;
$encryptionKey = self::getKey();
$encryptionKey = $this->getKey();
if ($definedIV = ($this->setInfo('predefinedIV', $this->isIVPredefined) === false)) {
$this->iv = substr($input, 0, $ivLen);
$cTextOffset += $ivLen;
Expand Down
2 changes: 1 addition & 1 deletion src/Symmetric/OpenSSL/StringCrypt.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ class StringCrypt
*
* @param string $tag Tag for decryption only
*/
public function setTag(string $tag)
public function setTag(string $tag): void
{
$this->tag = $tag;
}
Expand Down
Loading

0 comments on commit a659264

Please sign in to comment.