Password Encryption and Decryption Technique in PHP

Advertisement

I’ve noticed that many of my friends are storing password in database without encrypting them. This is really a bad technique because if somebody who has access of the database can easily know the password of the particular person.

The best functions available in PHP for encryption are md5() and sha1(). These both are one way encryping mechanism i.e the string encrypted with md5() or sha1() can’t be decrypted to original string. You might be then wondering how to validate the original string with the encrypted string then you can do this by encrypting the original string and compare both string,

$string='roshan'; //this is original string
$encrypted='d6dfb33a2052663df81c35e5496b3b1b'; //which is md5('roshan')
if(strcmp(md5($string),$encrypted)==0)
  echo"Valid string";
else
  echo"Invalid string";

md5() and sha1() provides the same functinality of encryption in php but they differ in a simple way that md5() generates 32 characters of encrypted string which sha1() generates same of 40 characters.Now let’s look at the different scenario where you need to store the password encrypted in the database and you need to send the originalpasword to the member of your website. In this situation, you can’t use md5() or sha1() because you need to reset the password once if forget it. Now at this time functions like base64_encode() and gzdeflate() comes handy.You can decrypt the password encrypted with base64_encode() with base64_decode() and the same applies for gzdeflate() with gzinflate().

For those guyz who really wants to encrypt and store the password with their own encryption and decryption mechanism then here is the function i’ve used in some of my web projects.


//function to encrypt the string
function encode5t($str)
{
  for($i=0; $i<5;$i++)
  {
    $str=strrev(base64_encode($str)); //apply base64 first and then reverse the string
  }
  return $str;
}

//function to decrypt the string
function decode5t($str)
{
  for($i=0; $i<5;$i++)
  {
    $str=base64_decode(strrev($str)); //apply base64 first and then reverse the string}
  }
  return $str;
}

In this function, i’ve encrypted the string 5 times with base64_encode and reversing the string with strrev() and for decrypting 5 times by reversing the string first then applying base64_decode() .

Tags: ,

Enter your email address and get free tutorials, tips and tricks of PHP, Ajax, JavaScript and CSS directly delivered to you email inbox:

36 Comments on “Password Encryption and Decryption Technique in PHP”

  • Sofia wrote on 13 January, 2008, 21:02

    You could also use mysql AES_ENCRYPT and AES_DECRYPT functions :) (http://dev.mysql.com/doc/refman/5.0/en/encryption-functions.html)

  • rayearth2601 wrote on 14 January, 2008, 2:24

    thanks for your info….
    it’s very useful

  • will wrote on 15 January, 2008, 21:06

    md5 has been found to collide under very rare circumstances. this means two different passwords (or other data) may generate the same hash-code. (32 characters unsalted).

    aes_encrypt and decrypt are great for encrypting personal data, but there’s no reason to decrypt a password; ever. In my experience, they are best used when storing payment card data (See the PCI-DSS website for more information, https://www.pcisecuritystandards.org/).

    SHA1 is 40 characters long (when stored unsalted); and serves me very well in managing passwords or other sensitive ‘one-direction’ data.

    FYI, base64_encode and decode are meant for attachment handling. I have (mistakenly) used them to store HTML data in a database with respect to sensitive information, but their intent is not for reversible encryption.

  • lion wrote on 17 January, 2008, 15:04

    Wow ! Nice article..

    Keep it up bro..

  • will wrote on 17 January, 2008, 16:21

    I also forgot to mention that base64_encode and decode are not recommended encryption / decryption techniques because the resulting data does not have a predictable length. In storing something like a password, this is a bad idea. However, for storing a sensitive file (ideally outside your database), this is a quick and easy approach.

    If you are using a flat-file database (like TXTSql), the following will probably not affect you.

    With AES_ENCRYPT and AES_DECRYPT in MySQL 4 and up, the resulting encrypted data always has a predictable length. With a fixed column size in the database, you can count on your application performing steadily. If you use the base64_ approach, the column has an unpredictable length, which will slow queries and data retreival from the database.

    The optimal way (in my experience) to handle a lost password is to generate a new one, apply an account flag (usually an activation key), and send the user a re-activation link.

    The advantages of this approach are: 1) users will never need to supply personally identifiable information to replace their password, 2) their password is never given away, 3) only the person handling mail received at the account’s email address will have access to re-activate the account, 4) you can force the user to change their password once the account is re-activated, 5) (the biggie), database performace is NEVER comprimised.

  • Someone wrote on 21 January, 2008, 21:13

    Base64 encoding is not difficult to reverse. It does not require a key to decrypt it or something alike. To me, that seems like a big flaw.

  • WebTenet wrote on 22 January, 2008, 13:59

    MySQL also provides the ENCODE() and DECODE() functions which can be used for handling passwords, but the manual says “AES_ENCRYPT() and AES_DECRYPT() can be considered the most cryptographically secure encryption functions currently available in MySQL”

  • tedivm wrote on 26 January, 2008, 0:15

    This technique doesn’t really accomplish anything useful, for numerous reasons.

    1- Anyone who knows the technique (which, to be fair, you did post on your website) can easily reverse it.

    2- By themselves, md5() and sha1() are horrible for encryption. Read up on time versus memory attacks, or look into things like rainbow tables.

    The best method is to have a password reset, as opposed to a password lookup, and to use something a bit more one way.

    Personally, I use sha256 and salt the password before hashing.

    For more information:
    http://phpsec.org/articles/2005/password-hashing.html

  • Roshan wrote on 31 January, 2008, 9:56

    ya i agree with you with storing the salt technique but sometime client ask for the password lookup rather than password reset and at the time you’ve to decrypt the password anyway…

  • Anonamoose wrote on 1 February, 2008, 23:03

    Using md5/sha1/sha256 is not encryption, they are one way hashing. If you can’t make the distinction then you shouldn’t be touching this stuff at all.
    For passwords hashing is fine (salted) and asynchronous encryption should be used for anything that needs to be reversed e.g. CC/personal information.
    Never EVER use the crypt functions in the database unless you use SSL connections to it! (even then I wouldn’t touch it) if you want to know why then google for it.
    Articles that glance over the details like this encourage script kiddies to do insecure things, please research such an important subject a bit more before posting.

  • Roshan wrote on 4 February, 2008, 6:59

    Anonamoose , I don’t agree with you. Do you have any idea hashing is part of encryption or not?? Show me any book related to cryptography and doesn’t discuss about md5 and sha algorithm??? How can you distinguish hashing from cryptography??

  • Tech Per wrote on 6 February, 2008, 14:41

    Actually, Roshan is quite right, but maybe a bit harsh about it :-)

    MD5 and SHA1 are not encryption methods, they are whats called hashing. It is a one-way operation, where you convert stuff like a password to a fixed lenght string you can store. You can think of it as encrypted, because you cannot get back to clear-text. But it is not encryption as such. There is no decypt method. BTW: Always using salting, to make the hash algorithms safe.

    Now, with respect to base64. This is *really* not encryption. That is just an *encoding* of data. Usually used to ensure, that text is stored as 7-bit ascii, when transferred through systems that might not support 8-bit charset. Like emails.

    There is *NO* key to decode (not decrypt) base64 encoded data. Base64 is as good as cleartext data, hence not encrypted at all, just encoded.

  • Matt wrote on 6 February, 2008, 17:16

    I hope you don’t write any software that stores my personal data…

  • Anonamoose wrote on 13 February, 2008, 22:40

    Ok I may of been a little harsh, Tech Per stated basically what I was thinking.
    I could take every letter of the alphabet and assign it a number, which using the terminology of the article would be ‘encryption’ but it is hashing or encoding (which can be different as well, it gets murky the more you dig), A one way hash simply makes it impossible (due to loss of information) to reverse the encoding and hence you get scrambling or ‘encryption’ as a side effect, it is however still a 1-to-1 mapping (in theory).
    True encryption however will not loose data, instead it maps the entire set to another seemingly random data set usually with some form key or process to get the information back.

  • Roshan wrote on 14 February, 2008, 4:40

    Anonamoose i agree with you. Encryption is different than hashing and encoding in the book of cryptography. But this article is mainly for the beginners and my objective is to convert the password into unreadable format. If you look at the basic meaning of encryption in dictionary
    http://dictionary.reference.com/browse/encryption
    which refer it as “to encipher or encode.”. So we think we need to complain dictionary to remove that meaning. Isn’t it ??

  • Anonamoose wrote on 17 February, 2008, 20:17

    Roshan I appreciate you want to help beginners and hope you do continue, but my fear is by ‘dumbing down’ some of the aspects you harm them in the long term. For instance the poster who sugested using the MySQL functions, you would have to be insane to do this if you want an even remotely secure application. Also look at the people linking your article, they do not question if it is safe or even the proper way of doing it, this is insane for security, if you don’t understand it don’t do it!.
    Hashing should always be ‘salted’ (not mentioned in the article) once again the removal of complexity to make it easier to follow also removes some of the security given by this technique. I do not mean to pick on you personally, it’s just I found your article and had some time to spare.

  • Dominus Chaos wrote on 27 February, 2008, 12:39

    I’ve found this tecnique somewhat usefull.
    I’m managing to get a password system with 2 parameters.( i could join 2 strings in one also)
    it will be:

    PASSWORD
    input_key [oper] mac_address = reservible_pswd.
    if i wanna install in other machine i’ll only have to calculate a new input_key (will be outputed) to give the save reservible_pswd with the new mac_adress.

    i can then STORE data in database with base64 and\or gzdeflate and somehow with the reservible_password.

    them i can keep the reversible password HASHED in a file.

    sorry for my bad english.

  • Bonafide wrote on 31 July, 2008, 13:19

    This IS a helpful article for beginners.
    If you are one, expand on this simple technique. Mix it up a bit.

    If you have any level of security concern, don’t use this because its way too obvious.

    Generally helpful comments on this site too – kudos

  • kapil wrote on 17 September, 2008, 7:20

    Thankx…. i was looking for custom function.. to encryption and decryption.. its easy and usefull..

    thankx SEO Expert..

  • the k wrote on 14 March, 2009, 20:51

    What is it with people thinking applying a poor “encryption” multiple times makes it any less poor? Generally, if you don’t see the flaws above commenters point out and understand what the big idea is, you might as well use no hashing at all and receive the same functionality and security with less work.

  • Rajasekar wrote on 3 April, 2009, 7:20

    I generated sha1() string in order to store a password in the table. But i want to know how to retrive back the original password as a normal string in order to send the password to the users who have submitted the forgotten request. I want to know is there any function that i can retireve the password in normal string form. coding done in PHP

    Please any one help me on this…

  • banu wrote on 22 April, 2009, 18:38

    Hi ,I am looking for a way to encrypt and decrypt a file that I’m going to store on the filesystem. I am looking for something like base 64 encode. but base 64 doesnt use a key to encode. I would like something that I can encode using key and decode using key. It should be able to encode and decode all kinds of files that I upload.

    Any help would be really appreciated.

    thanks,

  • Asylum wrote on 15 May, 2009, 0:41

    md5 and sha are hash algorithms, not encryption. Here are a few PHP encryption functions.
    crypt
    mcrypt

  • ray wrote on 16 May, 2009, 16:31

    Rajeskar, I’m sure every hacker in the world would love to know how to do that. But from what I’ve gathered (and I’m a “kiddie” at this) the whole point of using SHA1() is that it produces a hash or pseudo encrption of a string that CANNOT be decrypted. Its not so much an encryption as a “unique” (and I use the word with caution as it may not always necessarilly be unique) aspect or representation of the string that created it., but holding no information as to exactly what the original string looked like or how to get back to it. Its only use is to compare it against another hashed string to see if both hashes look like they probably (in fact “almost” certainly) came from the same original string (i.e. that the entered password is the same as the stored one) .

  • ray wrote on 16 May, 2009, 16:42

    Anonamoose has indicated in quite strong terms that the use of MySQL’s AES_ENCRYPT( )and AES_DECRYPT() functions is a very bad idea (although I personally see “insanity” and “ignorance” as very different conditions and consider myself to be suffering more from the latter than the former), but can anyone tell me why? I appreciate that for password security hashing the password and comparing against hashed entered passwords is the sensible method, but what about encryption of email addresses, credit card details, etc etc. Is the implication that use of AES_ENCRYPT() for this would also consitute a need for pyschiatric care? I suppose I COULD try the suggestion of Googling for something like “why-is-it-a-mad-idea-to-use-AES_ENCRYPT()” but then I really think they would need to take me a way in a van! Can anyone enlighten me?

  • ray wrote on 17 May, 2009, 14:24

    banu, I’m not an expert but since no-one else has replied I’ll make a couple of suggestions (please no-one bite my head off if they are naive!)..

    Take a look at GPG (Gnu Privacy Guard free open source) from http://www.gnupg.org

    Or failing that maybe there’s a way to zip your files with passwords? (just an off the cuff idea)

  • Jared kidambi wrote on 30 October, 2009, 16:04

    I tried it out and men, this is miracle. lovely work

  • k satyadeep wrote on 7 December, 2009, 18:29

    very useful info thanks

  • K. Matheny wrote on 23 January, 2010, 20:49

    I’ve always been taught that when storing sensitive data, it’s needs to be a one-way encryption, meaning there should be no decryption method. You should only be able to encrypt a string and say whether or not it matches another encrypted string to determine its validity.

    Not a bad article though.

  • Alessandro wrote on 24 August, 2010, 11:38

    Hash cracker is a web-service that allows you to encrypt your passwords
    or crack your hashed passwords with MD5, SHA1 or NTLM algorithms.
    You can also encode or decode texts with Base64 system.

    http://www.hash-cracker.com

    Video tutorial:

    http://www.youtube.com/watch?v=JVxdQPdGXec

  • Jonathan wrote on 8 February, 2011, 8:50

    This has to be one of the worst articles on PHP encryption / password storage I have ever seen. Sadly it ranks No. 1 in google for certain related search terms.

    Firstly, MD5 and SHA1 are HASHING ALGORITHMS – no encryption there – read a book

    Secondly, user passwords should NEVER be reversible – if someone forgets their password then they should be sent a randomly generated one and given the option (or be forced) to change it on next login.

    Third, your ‘encryption’ functions are lame – just use something like mcrypt with a decent algorithm.

  • Erick wrote on 15 June, 2011, 4:10

    I want to thank you for this ingenious “encryption” algorithm. Due to your ineptitude, and that of my client’s web development company, I found this algorithm used in production. I seriously hope that you quit development before you inflict any further damage.

  • Google chrome wrote on 15 March, 2012, 2:44

    very useful code thanks

Trackbacks

  1. T?cnicas de Criptografia e Descriptografia em PHP
  2. dropsafe : links for 2008-02-07
  3. links for 2008-02-07 | sun

Write a Comment

 


Copyright © 2014 Roshan Bhattarai's Blog. All rights reserved.
Powered by WordPress.org, Custom Theme and ComFi.com Calling Card Company.