How to encrypt long strings in PHP?
I'm using PHP's openssl_public_encrypt() to encrypt data us开发者_如何学JAVAing RSA. But it won't encrypt data larger than a certain size.
How can I get it to encrypt data of an arbitrary length?
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!
The php.net page has an excellent hint for this problem (as usual) http://www.php.net/manual/en/function.openssl-public-encrypt.php#95307
You can either:
- Encrypt the data using a symmetric encryption method, using a random key that is then encrypted using the public key of an asymmetric encryption method (The random key, encrypted with the public key, is necessary to the user who decrypts the data.)
- Encrypt the data using an asymmetric encryption method, after splitting the data in chunks of the size handled by the asymmetric encryption method
The first implements a hybrid cryptosystem. Using PHP and the openSSL extension you can use openssl_seal()
, which (since PHP 5.3.0) allows to set the cipher method (by default, RC4) and (since PHP 7.0.0) the initialization vector. If you aren't using PHP 7.x, or you want to write code compatible with PHP 5.3.3 and higher versions, and you want to be able the initialization vector, you could
use openssl_random_pseudo_bytes()
to generate the random key, openssl_encrypt()
to encrypt the data, and openssl_public_encrypt()
to encrypt the random key.
I would not use openssl_seal()
with a PHP version that doesn't allow me to set the cipher method (but then, I would not use that PHP version because it's not supported anymore), and I would not use RC4 as cipher method, on PHP versions that allows me to select the cipher method.
精彩评论