jmenezes
jmenezes

Reputation: 1926

PHP simple string encryption and decryption

Is there a simple function in PHP other than mcrypt() that can encrypt and decrypt a string.

I was trying out the code below, but that's too much for what I'm trying to do.

I'm trying to encrypt page numbers that are sent with a URL, so users will not be able to access a page simply by making changes to the page number in the browsers location bar. My page number has some other data too, that I do not want visible to users.

Example: http://www.example.com/p10:05 to http://www.example.com/895f852d22d558esc23

I don't need such high level encryption and decryption like in the code below. Just something that can do like in my example is sufficient.

Another reason I do not like using mcrypt, is because of the 2 == it adds to the end of a string.

$salt ='iodine';

    function simple_encrypt($text)
    {
        global $salt;
        return trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $salt, $text, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND))));
    }

    function simple_decrypt($text)
    {
        global $salt;
        return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $salt, base64_decode($text), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND)));
    }

    echo simple_encrypt('Hello')

Upvotes: 0

Views: 4576

Answers (1)

Maarten Bodewes
Maarten Bodewes

Reputation: 93948

MCrypt does not add those == characters to the string, the base 64 encoding does. It is possible to simply remove them. Just make sure that the base64 string is a multiple of 4 characters by adding them back again when the string is received.

Base 64 can contain the '/' and '+' characters by default (depending on the input). Replace them with URL safe - and _ characters.

The code shows MCRYPT_RIJNDAEL_256 which is not AES; it is Rijndael with a 256 bit block size. Using MCRYPT_RIJNDAEL_128 - which is AES - would be better. This still allows the code to encrypt up to 16 character number values and it will decrease the output size.

There is no need to generate an IV if ECB mode is used, so remove that part of the method. There is no need to add unnecessary work for the system random number generator.

The $salt value is actually the key value, better name it as such to avoid confusion.

Upvotes: 2

Related Questions