php: how to generate different output for same string
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
Answer
Solution:
To encrypt the same
plaintext
so that it generates differentciphertext
you change the key (and/orInitialization Vector (IV)
depending on the mode of the algorithm, like CBC).Example:
Both the same
IV
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 same
passphrase
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.
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.
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.
Usage: