Last active
July 5, 2022 11:52
-
-
Save ProjectOrangeBox/2a3ae6b0582d433915cc6f98388268d7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* | |
* This content is released under the MIT License (MIT) | |
* | |
* @author Don Myers | |
* @license http://opensource.org/licenses/MIT MIT License | |
* @link https://github.com/ProjectOrangeBox | |
*/ | |
class ssl | |
{ | |
public static function create(int $bits = 2048, string $folder = null): bool | |
{ | |
$folder = ($folder) ? rtrim($folder, '/') : __DIR__; | |
$public = $folder . '/public.key'; | |
$private = $folder . '/private.key'; | |
if (!is_writable($folder)) { | |
throw new \Exception('Key folder is not writable.'); | |
} | |
$config = [ | |
'private_key_bits' => $bits, | |
'private_key_type' => OPENSSL_KEYTYPE_RSA, | |
]; | |
$privateKey = openssl_pkey_new($config); | |
openssl_pkey_export_to_file($privateKey, $private); | |
$publicKey = openssl_pkey_get_details($privateKey); | |
return file_put_contents($public, $publicKey['key']) > 0; | |
} | |
public static function encrypt(string $data, string $keyFile = null): string | |
{ | |
$keyFile = ($keyFile) ?? __DIR__ . '/public.key'; | |
if (!file_exists($keyFile)) { | |
throw new \Exception('Count not locate key file ' . basename($keyFile)); | |
} | |
$key = openssl_pkey_get_public('file://' . $keyFile); | |
if (!$key) { | |
throw new \Exception('Could not get public key'); | |
} | |
$details = openssl_pkey_get_details($key); | |
$length = ceil($details['bits'] / 8) - 11; | |
$output = ''; | |
while ($data) { | |
$chunk = substr($data, 0, $length); | |
$data = substr($data, $length); | |
$encrypted = ''; | |
if (!openssl_public_encrypt($chunk, $encrypted, $key)) { | |
throw new \Exception('Failed to encrypt data'); | |
} | |
$output .= $encrypted; | |
} | |
return $output; | |
} | |
public static function decrypt(string $data, string $keyFile = null): string | |
{ | |
$keyFile = ($keyFile) ?? __DIR__ . '/private.key'; | |
if (!file_exists($keyFile)) { | |
throw new \Exception('Count not locate ' . basename($keyFile)); | |
} | |
$key = openssl_pkey_get_private('file://' . $keyFile); | |
if (!$key) { | |
throw new \Exception('Could not get private key'); | |
} | |
$details = openssl_pkey_get_details($key); | |
$length = ceil($details['bits'] / 8); | |
$output = ''; | |
while ($data) { | |
$chunk = substr($data, 0, $length); | |
$data = substr($data, $length); | |
$decrypted = ''; | |
if (!openssl_private_decrypt($chunk, $decrypted, $key)) { | |
throw new \Exception('Failed to decrypt data'); | |
} | |
$output .= $decrypted; | |
} | |
return $output; | |
} | |
} /* end class */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment