Just a little note on [P.Peyremorte]'s note in manual's openssl_private_encrypt.
"- openssl_private_encrypt can encrypt a maximum of 117 chars at one time."
This depends on the length of $key:
- For a 1024 bit key length => max number of chars (bytes) to encrypt = 1024/8 - 11(when padding used) = 117 chars (bytes).
- For a 2048 bit key length => max number of chars (bytes) to encrypt = 2048/8 - 11(when padding used) = 245 chars (bytes).
... and so on
By the way, if openssl_private_encrypt fails because of data size you won't get anything but just false as returned value, the same for openssl_public_decrypt() on decryption.
"- the encrypted output string is always 129 char length. If you use base64_encode on the encrypted output, it will give always 172 chars, with the last always "=" (filler)"
This again depends on the length of $key:
- For a 1024 bit key length => encrypted number of raw bytes is always a block of 128 bytes (1024 bits) by RSA design.
- For a 2048 bit key length => encrypted number of raw bytes is always a block of 256 bytes (2048 bits) by RSA design.
... and so on
About base64_encode output length, it depends on what you encode (meaning it depends on the bytes resulting after encryption), but in general the resulting encoded string will be about a 33% bigger (for 128 bytes bout 170 bytes and for 256 bytes about 340 bytes).
I would then generalize a little [P.Peyremorte]'s note by:
<?php
private $ENCRYPT_BLOCK_SIZE = 200;private $DECRYPT_BLOCK_SIZE = 256;function encrypt_RSA($plainData, $privatePEMKey)
{
$encrypted = '';
$plainData = str_split($plainData, $this->ENCRYPT_BLOCK_SIZE);
foreach($plainData as $chunk)
{
$partialEncrypted = '';
$encryptionOk = openssl_private_encrypt($chunk, $partialEncrypted, $privatePEMKey, OPENSSL_PKCS1_PADDING);
if($encryptionOk === false){return false;}$encrypted .= $partialEncrypted;
}
return base64_encode($encrypted);}
protected function decrypt_RSA($publicPEMKey, $data)
{
$decrypted = '';
$data = str_split(base64_decode($data), $this->DECRYPT_BLOCK_SIZE);
foreach($data as $chunk)
{
$partial = '';
$decryptionOK = openssl_public_decrypt($chunk, $partial, $publicPEMKey, OPENSSL_PKCS1_PADDING);
if($decryptionOK === false){return false;}$decrypted .= $partial;
}
return $decrypted;
}
?>