Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encrypt and Decrypt String With Key PHP [duplicate]

Tags:

php

encryption

I'm looking for some functions to encrypt and decrypt strings in php using a key specified.

Thanks!

like image 719
Belgin Fish Avatar asked May 10 '10 21:05

Belgin Fish


2 Answers

A basic openssl implementation I've used before:

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;
    }
}

You would need to generate the RSA key pair. See here for information on how to do that. Storing the private key in the file itself is a bad idea. This is just an example. Ideally you would want the user to supply the private key at decryption time

like image 85
Mark Avatar answered Sep 28 '22 18:09

Mark


Start with this: http://www.ibm.com/developerworks/opensource/library/os-php-encrypt/

After that, have a look at Pascal MARTIN's answer in How do I encrypt a string in PHP?

like image 22
labratmatt Avatar answered Sep 28 '22 17:09

labratmatt