| 1 |
<?php |
| 2 |
/* |
| 3 |
* This file is part of the ManageWP Worker plugin. |
| 4 |
* |
| 5 |
* (c) ManageWP LLC <[email protected]> |
| 6 |
* |
| 7 |
* For the full copyright and license information, please view the LICENSE |
| 8 |
* file that was distributed with this source code. |
| 9 |
*/ |
| 10 |
|
| 11 |
class MWP_Crypter_PhpSecLibCrypter implements MWP_Crypter_Interface |
| 12 |
{ |
| 13 |
public function publicEncrypt($data, $publicKey) |
| 14 |
{ |
| 15 |
$this->requireLibrary(); |
| 16 |
|
| 17 |
$rsa = new Crypt_RSA(); |
| 18 |
$rsa->setEncryptionMode(CRYPT_RSA_SIGNATURE_PKCS1); |
| 19 |
$rsa->loadKey($publicKey, CRYPT_RSA_PUBLIC_FORMAT_PKCS1); |
| 20 |
|
| 21 |
$errorCatcher = new MWP_Debug_ErrorCatcher(); |
| 22 |
$errorCatcher->register(); |
| 23 |
$encrypted = $rsa->encrypt($data); |
| 24 |
$error = $errorCatcher->yieldErrorMessage(true); |
| 25 |
|
| 26 |
if ($encrypted === false && $error !== null) { |
| 27 |
throw new MWP_Worker_Exception(MWP_Worker_Exception::PHPSECLIB_ENCRYPT_ERROR, "Error while trying to use OpenSSL to encrypt a message.", array( |
| 28 |
'error' => $error, |
| 29 |
)); |
| 30 |
} |
| 31 |
|
| 32 |
return $encrypted; |
| 33 |
} |
| 34 |
|
| 35 |
public function publicDecrypt($data, $publicKey) |
| 36 |
{ |
| 37 |
$this->requireLibrary(); |
| 38 |
|
| 39 |
$rsa = new Crypt_RSA(); |
| 40 |
$rsa->setEncryptionMode(CRYPT_RSA_SIGNATURE_PKCS1); |
| 41 |
$rsa->loadKey($publicKey, CRYPT_RSA_PUBLIC_FORMAT_PKCS1); |
| 42 |
|
| 43 |
$errorCatcher = new MWP_Debug_ErrorCatcher(); |
| 44 |
$errorCatcher->register(); |
| 45 |
$decrypted = $rsa->decrypt($data); |
| 46 |
$error = $errorCatcher->yieldErrorMessage(true); |
| 47 |
|
| 48 |
// "Decryption error" is generated by the library when the public key is not correct. |
| 49 |
if ($decrypted === false && $error !== 'Decryption error') { |
| 50 |
throw new MWP_Worker_Exception(MWP_Worker_Exception::PHPSECLIB_DECRYPT_ERROR, "Error while trying to use OpenSSL to decrypt a message.", array( |
| 51 |
'error' => $error, |
| 52 |
)); |
| 53 |
} |
| 54 |
|
| 55 |
return $decrypted === false ? null : $decrypted; |
| 56 |
} |
| 57 |
|
| 58 |
private function requireLibrary() |
| 59 |
{ |
| 60 |
if (class_exists('Crypt_RSA', false)) { |
| 61 |
return; |
| 62 |
} |
| 63 |
|
| 64 |
require_once dirname(__FILE__).'/../../PHPSecLib/Crypt/RSA.php'; |
| 65 |
} |
| 66 |
} |
| 67 |
|