2

I saw this code:

<?php
class MyEncryption
{

    public $pubkey = '...public key here...';
    public $privkey = '...private key here...';

    public function encrypt($data)
    {
        if (openssl_public_encrypt($data, $encrypted, $this->pubkey))
            $data = base64_encode($encrypted);
        else
            throw new Exception('Unable to encrypt data. Perhaps it is bigger than the key size?');

        return $data;
    }

    public function decrypt($data)
    {
        if (openssl_private_decrypt(base64_decode($data), $decrypted, $this->privkey))
            $data = $decrypted;
        else
            $data = '';

        return $data;
    }
}


?>

What are samples of public_key? What kind of public key should be put on $pubkey? Should it be base_64encoded or not? How do I generate one?

I added:

$privKey = openssl_pkey_new();

And all I got is $privKey==false

6
  • Is this a specific script or your own work?
    – Moseleyi
    Dec 18, 2012 at 9:12
  • 3
    from where, you got this code ?
    – GBD
    Dec 18, 2012 at 9:13
  • I got this from stackoverflow. I am learning.
    – user4951
    Dec 18, 2012 at 9:43
  • I said I saw a code. No I didn't write this.
    – user4951
    Dec 18, 2012 at 9:43
  • I just want to use a simple private and public. No need for anything complicated.
    – user4951
    Dec 18, 2012 at 10:44

1 Answer 1

2

The keys have to be generated together, as the public key is the "non-secret" key that can encrypt information so that only the private key is able to decrypt it. This is an example of Public-key cryptography.

If openssl_pkey_new fails (it will not return the key itself, only a resource that you can use to retrieve the actual keys), see the examples and links to alternatives in the comment section of the manual page.

And no, the keys should not base64-encoded. This is only done to the encrypted data in your methods. The reason that this is done in the class is probably because the original author wanted to transfer the encrypted data through some sort of non-binary-safe environment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.