Rietta
Rietta: Web Apps Where Security Matters
You are reading The Rietta Blog, a publication about the web since 2005.

OpenSSL: Encrypt Data With an RSA Key With PHP

This post is part of our ongoing Encryption Series that provides in-depth coverage of OpenSSL. To learn more about encryption key generation, management, and use please see the posts in the Encryption category. Our tips and tricks are immediately applicable with examples that you can use right away. If you like this article, you may be interested in the Raspberry Pi crypto key management project as well as Rietta’s Application Security Learning Center, our catalog of video resources on how to succeed with web application security.


Web application security is built upon a series of interconnected building blocks.

Last year, I wrote about how Generating an RSA Key from the Command Line in OpenSSL could support encrypting or validating data in an unattended manner (where the password is not required to encrypt). A few weeks before that, I posted about how to Encrypt a File with a Password from the Command Line using OpenSSL.

Knowing how to generate an encryption key is great, but knowing how to use it in your application is even better.

So here is an example PHP function that can encrypt arbitrary data, including strings and arrays, using an RSA public key generated with the example in the previous article.

The Code to Encrypt and Serialize

encrypt_data.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  <?php
    function encryptData($dataToEncrypt) {

      // Will hold the encrypted data  
      $sealed ="";
      $ekeys="";
      $pubKey[] =   openssl_pkey_get_public( file_get_contents( "public.pem" ) );
      $result = openssl_seal( gzcompress( $dataToEncrypt ), $sealed, $ekeys, $pubKey);

      /* Encrypt the Data using OpenSSL seal, which applies an RC4 cipher across the data and encrypts the session key with the array of envelope keys */

      return array( encdata' => base64_encode($sealed) , ‘enckey' => base64_encode( serialize($ekeys)) );
    } // end encryptData 

    // Say "Hello, World!" in an Encrypted Format  
    echo  serialize(encryptData("Hello, World!"));
  ?>

The Output from this Code

On my system, running this script returns a serialized array as a single line of text. In this example, newlines and tabs have been added for readability.

The resulting serialized array (newlines added for readability).
1
2
3
4
5
6
7
8
9
a:2:{
  s:7:"encdata";s:28:"K5LPNyfUcd9TOoLgRGKhuncS8wBk";
  s:6:"enckey";
  s:368:"YToxOntpOjA7czoyN TY6Iq2QT1YZBFeLrn6bieV3O2gEYAD3vrAwoCNpsyBnmkUP1MW4YB0TiFS
        fygjnioTUllCC5vzCvru rk5v6p107Yf4RI/+xREKl9Qq1vwuaABTJ6tsBO01gNWRfNoCIdGOziJm64FAcM
        7ULjaC0i+DnhgKmsX 9nUlhCv5K1f4ZWB8i3hiQ+q5PvTkbMa2djhRdJpNUNQokWceBR9/twwXOi3h+9xVz
        Dxe1wnBK4sEL My/nwlyNcdrPKo1YY/R+QLg0da61/Fo6nma308XPI9B4iWepnCCQAsJB/gSlj0iVWEEJOn
        dj/QY2+XIB JWDU1Y04vIzjGIoqT0JTBjD4PJF9/gqEiO30=";
}

A good encryption scheme will generate different cipher text each time it is run. Therefore, running the script multiple times will result in different looking random data in the encdata and enckeys fields as a different random session key for each run.

Or, If You Want to Use JSON

The serialize function is a specific format to PHP. If you want to use JSON instead, you can do so with something like this at the end of the encryptData function.

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
  function encryptData($dataToEncrypt) {
    // ...
    // Code as seen in the example above
    // ...
    foreach($ekeys AS $key => $value) {
    $ekeys_ascii[$key] = base64_encode($value);
    }  return array(
          'encdata'=>base64_encode($sealed)
           ,'enckey'=>json_encode($ekeys_ascii)
     );
  } // end encryptData
?>

In Conclusion

OpenSSL is a cryptographic foundation upon which you can build some very powerful, flexible, and will help improve the security of your web applications.

Invitation to the Web Application Topics Newsletter

This post is part of the Web Application Topics series. If you are interested in having future issues sent directly to you by e-mail, please sign up for free, today. For back issues, see the Web Application Topics category on this blog.

About Frank Rietta

Frank Rietta's photo

Frank Rietta is specialized in working with startups, new Internet businesses, and in developing with the Ruby on Rails platform to build scalable businesses. He is a computer scientist with a Masters in Information Security from the College of Computing at the Georgia Institute of Technology. He teaches about security topics and is a contributor to the security chapter of the 7th edition of the "Fundamentals of Database Systems" textbook published by Addison-Wesley.