views:

54

answers:

3

I don't want to use Open SSL or any very big none-built-in libraries for this. I only want to be able to encrypt a string with a key so you can't decrypt it without it.

By the way, i already did a long search on stackoverflow and i've checked out those unsecure ways but i want something robust like md5 (which can be decrypted with a key).

Thanks

+1  A: 

Something like mcrypt is probably what you're looking for. It does two way encryption which hashing functions like MD5 do not do.

Try this PHP5 class for encryption using mcrypt. In this case it's using blowfish encryption. You'll want to change the key for each site you use it on. If you don't use it at least it may guide you on writing your own version of it.

<?php

class Encryption
{
    const CYPHER = 'blowfish';
    const MODE   = 'cfb';
    const KEY    = '7QQvcT9Ga7R6QC3';

    public function encrypt($plaintext)
    {
        $td = mcrypt_module_open(self::CYPHER, '', self::MODE, '');
        $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
        mcrypt_generic_init($td, self::KEY, $iv);
        $crypttext = mcrypt_generic($td, $plaintext);
        mcrypt_generic_deinit($td);
        return $iv.$crypttext;
    }

    public function decrypt($crypttext)
    {
        $plaintext = '';
        $td        = mcrypt_module_open(self::CYPHER, '', self::MODE, '');
        $ivsize    = mcrypt_enc_get_iv_size($td);
        $iv        = substr($crypttext, 0, $ivsize);
        $crypttext = substr($crypttext, $ivsize);
        if ($iv)
        {
            mcrypt_generic_init($td, self::KEY, $iv);
            $plaintext = mdecrypt_generic($td, $crypttext);
        }
        return $plaintext;
    }
}

?>

Usage:

$encrypted_string = Encryption::encrypt('this is a test'); // Åž-\Ž“kcþ1ÿ4gî:Xƒã%
$decrypted_string = Encryption::decrypt($encrypted_string); // this is a test
John Conde
A: 

simplest way is to encrypt string using XOR operator

oraz
A: 

Most proposals will leave out two things key to security:

1: the nonce. Any secure mode of operation will take a nonce (or "IV") which has to be different for every encryption operation. This makes it harder for the attacker to exploit relationships between distinct encryption operations to learn about the plaintext: a trivial example is that the same plaintext encrypted twice with different nonces produces different ciphertexts.

2: the MAC. Unless you are a professional cryptographer, you should treat this as essential whenever you do encryption. This is a code that checks the integrity of the message, and ensures that only real ciphertext encrypted with that key will decrypt.

I strongly recommend using AES in either EAX or GCM mode; they have flexible nonce handling and manage both encryption and authentication in one package, with good solid proofs behind them.

Paul Crowley