Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to encrypt long strings in PHP?

I'm using PHP's openssl_public_encrypt() to encrypt data using RSA. But it won't encrypt data larger than a certain size.

How can I get it to encrypt data of an arbitrary length?

like image 682
Paul J Avatar asked Jun 08 '11 11:06

Paul J


1 Answers

RSA, using PKCS1 padding, only lets you do do strings that are the length the key (in bytes) - 11. This isn't an OpenSSL or PHP restriction but rather an RSA restriction.

If you want to do longer strings using the openssl_* set of functions use openssl_seal and openssl_open. openssl_seal generates a random string, encrypts it with RSA and then encrypts the data you're actually trying to encrypt with RC4 using the previously mentioned random string as the key.

phpseclib, a pure PHP RSA implementation, takes a different approach. If you insist on encrypting a string larger than the RSA key it'll split that string into chunks that are the max size RSA can handle and then concatenate the results.

The phpseclib OpenSSL Interoperability page discusses how you can use phpseclib to do the same thing as openssl_seal / openssl_open.

Hope that helps!

like image 129
neubert Avatar answered Sep 19 '22 13:09

neubert