| 1 |
<?php |
| 2 |
/** |
| 3 |
* Cryptography: Cryption |
| 4 |
* |
| 5 |
* @package SimplePay |
| 6 |
* @subpackage Core |
| 7 |
* @copyright Copyright (c) 2022, Sandhills Development, LLC |
| 8 |
* @license http://opensource.org/licenses/gpl-2.0.php GNU Public License |
| 9 |
* @since 4.12.1 |
| 10 |
*/ |
| 11 |
|
| 12 |
namespace SimplePay\Core\Cryptography; |
| 13 |
|
| 14 |
use Exception; |
| 15 |
|
| 16 |
/** |
| 17 |
* Cryption class. |
| 18 |
* |
| 19 |
* @since 4.12.1 |
| 20 |
*/ |
| 21 |
class Cryption { |
| 22 |
|
| 23 |
/** |
| 24 |
* Encrypts data using RSA public key. |
| 25 |
* |
| 26 |
* @param string $data Data to encrypt. |
| 27 |
* @return string|bool Base64 encoded encrypted data or false on failure. |
| 28 |
*/ |
| 29 |
public function encrypt( $data ) { |
| 30 |
// Check if openssl is enabled. |
| 31 |
if ( ! extension_loaded( 'openssl' ) ) { |
| 32 |
return false; |
| 33 |
} |
| 34 |
|
| 35 |
try { |
| 36 |
// Get the public key directly from the file. |
| 37 |
$public_key = file_get_contents( |
| 38 |
plugin_dir_path( SIMPLE_PAY_MAIN_FILE ) . 'data/etc/public_key.pem' // @phpstan-ignore-line |
| 39 |
); |
| 40 |
|
| 41 |
if ( false === $public_key ) { |
| 42 |
return false; |
| 43 |
} |
| 44 |
|
| 45 |
// Encrypt data with OAEP padding using OpenSSL. |
| 46 |
$encrypted_data = ''; |
| 47 |
$encryption_success = openssl_public_encrypt( |
| 48 |
$data, |
| 49 |
$encrypted_data, |
| 50 |
$public_key, |
| 51 |
OPENSSL_PKCS1_OAEP_PADDING // Set padding to OAEP. |
| 52 |
); |
| 53 |
|
| 54 |
if ( ! $encryption_success ) { |
| 55 |
return false; |
| 56 |
} |
| 57 |
|
| 58 |
// Encode the encrypted data in Base64 to send as a string. |
| 59 |
$base64_encrypted_data = base64_encode( $encrypted_data ); |
| 60 |
|
| 61 |
// Return base64 encoded encrypted data. |
| 62 |
return $base64_encrypted_data; |
| 63 |
} catch ( Exception $e ) { |
| 64 |
return false; |
| 65 |
} |
| 66 |
} |
| 67 |
|
| 68 |
/** |
| 69 |
* Check if openssl is enabled. |
| 70 |
* |
| 71 |
* @return bool |
| 72 |
*/ |
| 73 |
public function is_openssl_enabled() { |
| 74 |
return extension_loaded( 'openssl' ); |
| 75 |
} |
| 76 |
} |
| 77 |
|