0

I want to encrypt large strings using public key and store in file. And after that read the contents of file and decrypt it using private key. How can I do that. Is there any default function or code available in php.

Kaushal Kumar
  • 1,237
  • 1
  • 12
  • 21

3 Answers3

1

How large is the text you're wanting to encrypt? You can't have plaintext larger than the key length (ie. modulo) in RSA. What's most often done in these instances is that a symmetric cipher key is encrypted and the plaintext is then encrypted with that key.

PHP's openssl_seal() and openssl_open() functions (assuming you have the openssl extension installed) do this using the RC4 cipher.

neubert
  • 15,947
  • 24
  • 120
  • 212
0

Checkout OPENSSL documentation for PHP as you need to know how to handle PKI. You will find every information you need there.

Here is the link

Antoniossss
  • 31,590
  • 6
  • 57
  • 99
-1

You can do this using Zend Framework 2 (Zend\Crypt\PublicKey)

ZF2 : Public key cryptography

Example (from the docs from above link!)

use Zend\Crypt\PublicKey\Rsa;

$rsa = Rsa::factory(array(
    'public_key'    => 'public_key.pub',
    'private_key'   => 'private_key.pem',
    'pass_phrase'   => 'test',
    'binary_output' => false
));

$text = 'This is the message to encrypt';

$encrypt = $rsa->encrypt($text);
printf("Encrypted message:\n%s\n", $encrypt);

$decrypt = $rsa->decrypt($encrypt);

if ($text !== $decrypt) {
    echo "ERROR\n";
} else {
    echo "Encryption and decryption performed successfully!\n";
}

(edit: whitespace added to code)

Jeroen
  • 982
  • 1
  • 6
  • 14