1

I am very not experienced with certs and keys. I have to store a private key for a third party API in my database. I have a key to encrypt that. This is what I did in PHP

$private_key = "----BEGIN PRIVATE KEY---\nABCDBLAH\n---END PRIVATE KEY----\n"
// The encryption and storing part - 1
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
$encrypted = openssl_encrypt($data, 'aes-256-cbc', 'mykey', 0, $iv);
$encrypted_data = $encrypted .':'base64_encode($iv);
//store in the database

//retrieve later
$parts = explode(':',$encrypted_data);
$private_key= openssl_decrypt($parts[0], 'aes-256-cbc', 'mykey', 0, base64_decode($parts[1]));
// 2
Use in the API.

If I ignore the part between 1 and 2 for storing and retrieving the key from the database, the API and everything works correct which means there is something wrong in storing and retrieving the key. What I am I doing wrong here? If this is not the right way, what way should I use? Please help me.

Note: /n part in the private key. If I don't encrypt, /n doesn't matter and the API works.

user1429322
  • 1,266
  • 2
  • 24
  • 38
  • 1
    What if `$encrypted` contains a `:`? – SLaks May 27 '15 at 20:47
  • 1
    If would use mcrypt_encrypt and mcrypt_decrypt for strings. Check out the documentation in PHP's site: http://php.net/manual/en/function.mcrypt-encrypt.php and http://php.net/manual/en/function.mcrypt-decrypt.php – Ron Dadon May 27 '15 at 20:49
  • @SLaks I am not sure if openssl_encrypt gives characters like ':' – user1429322 May 27 '15 at 20:50
  • 1
    @user1429322: Ciphertext can and will contain arbitrary bytes. – SLaks May 27 '15 at 20:51
  • @SLaks Agreed. But the problem is not because of that. I didn't see any ':' while debugging. So ':' might become an issue but that is not the issue I have. – user1429322 May 27 '15 at 20:53

1 Answers1

0

What I am I doing wrong here?

Using base64_encode() on $encrypted would prevent data loss from database encoding.

However, there are a lot of other things you're doing wrong that affect the security of your scheme rather than merely prevent it from functioning.

Look at this answer for a comprehensive guide on how to implement encryption securely.

Scott Arciszewski
  • 33,610
  • 16
  • 89
  • 206