0

I have to encrypt the generated symmetric key (AES-256-CBC) with asymmetric encryption in PHP. I got a public certificate (CER file) I should use. I try to do it like this:

$fp = fopen('publickey.cer', 'r');
$pub_key = fread($fp, filesize('publickey.cer'));
fclose($fp);

openssl_public_encrypt($enc, $final, $pub_key, OPENSSL_PKCS1_PADDING);

where $enc is my symmetric key

I'm receiving output ($final) which is incorrect.

The working code in Java that works fine looks like this:

Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding") ;
cipher.init(Cipher.ENCRYPT_MODE, x509Certificate.getPublicKey());
return cipher.doFinal(bytes) ;

How to transform it into PHP?

Prabhu Nandan Kumar
  • 1,205
  • 12
  • 22
  • You need to extract the public key from the certificate - just use [openssl_csr_get_public_key](https://www.php.net/manual/de/function.openssl-csr-get-public-key.php) – Michael Fehr Apr 03 '21 at 15:46
  • Can you provide a working example ? PHP.NET doesn't have any example thats work for me. – Maciej Adrjanowicz Apr 03 '21 at 16:20
  • Place this line: $pub_key = openssl_csr_get_public_key($pub_key); **before** you encrypt ("openssl_public_encrypt") – Michael Fehr Apr 03 '21 at 22:06
  • It doesn't work right. My code is: $fp = fopen('publickey.cer', 'r'); $pub_key = fread($fp, filesize('publickey.cer')); fclose($fp); $pub_key = openssl_csr_get_public_key($pub_key); openssl_public_encrypt($enc, $final1, $pub_key); I getting error: Warning: openssl_public_encrypt(): key parameter is not a valid public key – Maciej Adrjanowicz Apr 04 '21 at 12:46

1 Answers1

0

You can use phpseclib for this & refer PHP RSA examples.

Load library using your uploaded file path & initiate class:

include('Crypt/RSA.php');
$rsa = new Crypt_RSA();

Encryption: You can use encryption mode as PKCS1Padding or OAEP.

$public_key="";
$plaintext = 'Hello world'; //string to encrypt

$rsa->loadKey($public_key); 
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1); //PKCS1Padding
//$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_OAEP); //OAEP

$ciphertext = $rsa->encrypt($plaintext);

Decryption :

$private_key="";

$rsa->loadKey($private_key); // private key
$text = $rsa->decrypt($ciphertext);
Priya
  • 23
  • 6