php: how to generate different output for same string

542

Is there some way to generate different output for same given string, here is example:

echo md5('test');

That always generates samefb469d7ef430b0baf0cab6c436e70375 for the given input. How do I generate different encrypted text each time and be able to decrypt it later if needed ?

I have seen functions such asmd5,base64_encode,crypt,sha1, etc but they generate same output and secondly I cannot decrypt later if needed.

P.S: I know I can go with one way encryption and compare encrypted texts but for a particular scenario, I have requirement to be able to decrypt text completely if needed later however I am not able to figure out if there is some way or function in php for it.

Any help will be greatly appreciated. Thanks

182

Answer

Solution:

To encrypt the sameplaintext so that it generates differentciphertext you change the key (and/orInitialization Vector (IV) depending on the mode of the algorithm, like CBC).

Example:

$string = 'Some Secret thing I want to encrypt'; 
$iv = '12345678'; 
$passphrase = '8chrsLng'; 

$encryptedString = encryptString($string, $passphrase, $iv); 
// Expect: 7DjnpOXG+FrUaOuc8x6vyrkk3atSiAf425ly5KpG7lOYgwouw2UATw== 

function encryptString($unencryptedText, $passphrase, $iv) { 
  $enc = mcrypt_encrypt(MCRYPT_BLOWFISH, $passphrase, $unencryptedText, MCRYPT_MODE_CBC, $iv); 
  return base64_encode($enc); 
}

Both the sameIV and thepassphrase must be used when decrypting inCBC mode. Thepassphrase MUST be kept a secret (from eavesdroppers) while theIV can be transmitted in the clear.

You CAN (but should not) use the samepassphrase for every message/data but you should ALWAYS change theIV for each message/data.

This is the basics of encryption but depending on you needs you may need to modify your architecture to keep the system secure.

511

Answer

Solution:

md5 is a hash method, not an encryption.

in short. there is no "good" way back from md5.

base64_encode and base64_decode and be used to transport messages, but it is no decryption.

please google on the topic RSA, ROT-13 or basic encryption with php.

67

Answer

Solution:

I have created this class (Thanks to @Sani Huttunen for the idea) for the purpose. It allows to have differ text generated each time even for same input text and decodes it successfully as well.

class Encoder
{
    private static $prefix = '@[email protected]';

    public static function php_aes_encrypt($text, $key)
    {
        if (!trim($text)) {
            return '';
        }

        $iv = self::generateRandomString();
        $key = self::mysql_aes_key($key);

        $pad_value = 16 - (strlen($text) % 16);
        $text = str_pad($text, (16 * (floor(strlen($text) / 16) + 1)), chr($pad_value));
        $ciphertext = mcrypt_encrypt(
           MCRYPT_RIJNDAEL_128,
           $key,
           $text,
           MCRYPT_MODE_CBC,
           $iv
        );

        $ciphertext = self::getPrefix() . base64_encode($ciphertext . $iv);
        return $ciphertext;
    }

    public static function php_aes_decrypt($text, $key)
    {
        $text = str_replace(self::getPrefix(), '', $text);
        $text = base64_decode($text);

        if (!trim($text)) {
            return '';
        }

        $iv = substr($text, -16);
        $text = str_replace($iv, '', $text);

        $key = self::mysql_aes_key($key);
        $text = mcrypt_decrypt(
           MCRYPT_RIJNDAEL_128,
           $key,
           $text,
           MCRYPT_MODE_CBC,
           $iv
        );

        return rtrim($text, "\0..\16");
    }

    private static function mysql_aes_key($key)
    {
        $new_key = str_repeat(chr(0), 16);

        for ($i = 0, $len = strlen($key); $i < $len; $i ++) {
            $new_key[$i % 16] = $new_key[$i % 16] ^ $key[$i];
        }

        return $new_key;
    }

    private static function getPrefix()
    {
        return base64_encode(self::$prefix);
    }

    public static function isEncrypted($ciphertext)
    {
        $isEncrypted = (false !== strpos($ciphertext, self::getPrefix()));
        return $isEncrypted;
    }

    private static function generateRandomString()
    {
        return substr(sha1(rand()), 0, 16);
    }
}

Usage:

$encrypted = Encoder::php_aes_encrypt('my test string', 'key');
echo $encrypted . '<br>';
echo Encoder::php_aes_decrypt($encrypted, 'key');

People are also looking for solutions to the problem: php - Weird date values SQL retrieval from the database with a BETWEEN operator

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.