1

I have this code to create a RSA 4096 public and private key to encrypt and decrypt a string.

Code:

<?php
$config = array(
    "config" => "C:/xampp/php/extras/openssl/openssl.cnf",
    "private_key_bits" => 4096,
    "private_key_type" => OPENSSL_KEYTYPE_RSA
);

// Create the private and public key
$res = openssl_pkey_new($config);

// Extract the private key from $res to $privKey
openssl_pkey_export($res, $privKey);

// Extract the public key from $res to $pubKey
$pubKey = openssl_pkey_get_details($res);
$pubKey = $pubKey["key"];

$data = 'Hello, World!';

// Encrypt the data to $encrypted using the public key
openssl_public_encrypt($data, $encrypted, $pubKey);

echo $encrypted;

// Decrypt the data using the private key and store the results in $decrypted
openssl_private_decrypt($encrypted, $decrypted, $privKey);

echo $decrypted;
?>

It creates the keys, encrypts data string (Hello, World!) but when tries to decrypt encrypted string, an error occurs:

Warning: openssl_private_decrypt(): key parameter is not a valid private key in C:\xampp\htdocs\rsa\index.php on line 26

2 Answers 2

1

Ok, this worked for me:

Change openssl_pkey_export($res, $privKey); to openssl_pkey_export($res, $privKey, NULL, $config);.

1
  • You may want to store the key in a protected (PKCS#12) key container or something similar. Storing the plain bytes is of course pretty dangerous. Similarly, for your scheme to be useful, the public key needs to be trusted at the receiver. Jan 16, 2020 at 0:54
-1

You don't need to export the key private like that, at least not until you save it somewhere secure:

$config = array(
    "private_key_bits" => 4096,
    "private_key_type" => OPENSSL_KEYTYPE_RSA
);

$pki     = openssl_pkey_new($config);
$public  = openssl_pkey_get_public(
    openssl_pkey_get_details($pki)['key']
); // why on earth did they implement it like this? so clunky.
$private = openssl_pkey_get_private($pki);

$data = 'Hello, World!';

openssl_public_encrypt($data, $encrypted, $public);
openssl_private_decrypt($encrypted, $decrypted, $private);

var_dump(
    bin2hex($encrypted),
    $decrypted
);
1
  • I guess that storing and retrieving a private key can be considered a rather valid use case. Not storing it is rather dumb, especially for RSA where key pair generation is expensive. Jan 16, 2020 at 0:53

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.