2

I'm trying to use PHP and OpenSSL to encrypt some data using a public key, and then decrypt it again.

I generated a public.key and private.key using this code:

// generate private key
$privateKey = openssl_pkey_new(array(
    'private_key_bits' => 1024,
    'private_key_type' => OPENSSL_KEYTYPE_RSA,
));
// write private key to file
openssl_pkey_export_to_file($privateKey, 'private.key');
// generate public key from private key
$publicKey = openssl_pkey_get_details($privateKey);
// write public key to file
file_put_contents('public.key', $publicKey['key']);
// clear key
openssl_free_key($privateKey);

My code to encrypt and decrypt is basically straight from the PHP documentation:

// data to encrypt
$data = "This is a long string or other bit of data that i want to encrypt";

// ==== ENCRYPT ====

// read public key
$publicKey =  file_get_contents("public.key");
$publicKey = openssl_get_publickey($publicKey);

// encrypt data using public key into $sealed
$sealed = '';
openssl_seal($data, $sealed, $ekeys, array($publicKey));
openssl_free_key($publicKey);

// ==== DECRYPT ====

// get private key to decrypt with
$privateKey = file_get_contents("private.key");
$privateKey = openssl_get_privatekey($privateKey);

// decrypt data using private key into $open
$open = '';
openssl_open($sealed, $open, $env_key, $privateKey);
openssl_free_key($privateKey);


// display decrypted data:
echo "<p>Decrypted data: ".$open;

Anyone got any clue why it is not working, or at least a way to find out what error is happening?

2
  • First of all, check the values of all variables to make sure they contain what you think they should contain :) Commented Aug 16, 2012 at 12:12
  • @Jack Cheers yes I think everything is as it should be. Its just refusing to decrypt the data as far as I can tell. I've pasted an example here: pastebin.com/HMGg7FSg Commented Aug 16, 2012 at 12:22

1 Answer 1

2

Did you forget this statement?

$env_key = $ekeys[0];

I found my answer by reading the example code for openssl_seal()

Sign up to request clarification or add additional context in comments.

1 Comment

Yes! Envelope keys, that was it, thanks v much! I wish there was better documentation on the function description about that

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.