Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations MikeeOK on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to Encrypt and Decrypt text?

Status
Not open for further replies.

paispatin

Technical User
Oct 21, 2003
62
A1
Dear all,

What should I do to encrypt and decrypt any text with simple PHP function?

I could encrypt any text with this function:
$mytext="what";
$encrypt_text=md5($mytext);

or
$encrypt_text=trim($mytext);
Well, how to decrypt this function?
Maybe anyone could give other function to encrypt and decrypt the text?

Thank you in advance
 
You can't decrypt MD5. MD5 is not an encryption algorithm, but rather a hashing algorithm. It was designed to be a one-way cypher.


trim()? That function just removes whitespace from the beginnings and ends of strings. It's not any kind of cypher at all.

I recommend you start by taking a look at the mcrypt function family documentation in the PHP online manual:
Want the best answers? Ask the best questions: TANSTAAFL!!
 
for encrypting and decrypting I use the following functions

Code:
function encrypt($key, $plain_text)
{
// returns encrypted text
// incoming: should be the $key that was encrypt
// with and the $plain_text that wants to be encrypted

  $plain_text = trim($plain_text);

  /*
     We need a way to generate a _unique_ initialization vector
     but at the same time, be able to know how to gather our IV at both
     encrypt/decrypt stage.  My personal recommendation would be
     (if you are working with files) is to get the md5() of the file.
     In this example, however, I want more of a broader scope, so I chose
     to md5() the key, which should be the same both times. Note that the
IV
     needs to be the size of our algorithm, hence us using substr.
  */

  /* generate an initialization vector */
  $iv = substr(md5($key), 0,mcrypt_get_iv_size
(MCRYPT_CAST_256,MCRYPT_MODE_CFB));
  /* now we do our normal encrypting */ 
  $c_t = mcrypt_encrypt (MCRYPT_CAST_256, $key, $plain_text,
"cfb", $iv);

    return trim(chop(base64_encode($c_t)));
}

function decrypt($key, $c_t)
{
// incoming: should be the $key that you encrypted
// with and the $c_t (encrypted text)
// returns plain text

  // decode it first :)
  $c_t =  trim(chop(base64_decode($c_t)));

  /* generate an initialization vector */
  $iv = substr(md5($key), 0,mcrypt_get_iv_size
(MCRYPT_CAST_256,MCRYPT_MODE_CFB));
  /* now we do our normal decrypting */ 
  $p_t = mcrypt_decrypt (MCRYPT_CAST_256, $key, $c_t, "cfb",
$iv);

return trim(chop($p_t));
}

I found these functions at and they work fine for me
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top