How to encrypt password with PHP

1 Star2 Stars3 Stars4 Stars5 Stars (2 votes, average: 4.50 out of 5)

We will see how to encrypt information in PHP in order to store and exchange it safely. But first, we’ll do a little reminder on symmetric cryptography.

Encryption is an operation which is to alter the information to make it unreadable, but reversibly only to a specific person, who is able to decrypt that information by restoring its original form.

How did you decrypt and therefore access this information?

The answer is simple: when encrypts the information, we will use an encryption key. And this encryption key also allows you to do the opposite: to do decrypt the information.

AES encryption with PHP

After this little essential reminder on cryptography, we will be able to attack the practice.

We’ll see how encrypt and decrypt with the algorithm Rijndael , which is used for standard AES, thanks to the bookstore libmcrypt .

To do this properly, we will put everything in a class that will serve as a “Namespace” (although it is not object oriented programming because all the members are static)

And this is how it is used:

The operation is very simple: to encrypt and decrypt with mcrypt, just use the functions mcrypt_encryptand mcrypt_decrypt.

My these functions take a lot of parameters, which are most always the same for encryption and decryption, except $data of course (which contains the variable to encrypt).

So far pooling all in static variables within a class:

  • cipher
    This setting tells how mcrypt encryption algorithm used. Indeed, libmcrypt offers many encryption algorithms (just over 40), you will find the list here: mcrypt.ciphers.php
  • Key
    This parameter is simply the encryption key which I mentioned above, which is used to encrypt and decrypt the message.
    And that’s not entirely true, you can not use any any string in key size is fixed and depends on the algorithm used.
    Rather than directly using a key, which look like this: a7af2934b9c8ca2e346314bea5cf3a8fa string is used much easier to remember, making office word password .
    Then a valid key you will generate from this password with a simple hash function, md5in this case. You have to choose your password features, and it must remain secret
  • Mode
    The procedure, another key concept (dare I say) cryptography.
    We will see below what it is.

Also, I used functions base64_encodeand base64_decodeto “encapsulate” the encrypted data (and same for decrypt, inevitably, since it is the reciprocal). It is not mandatory, and it is by no means an additional security measure. This is just to avoid encoding problems (character) because special characters. Base64 produces character strings that only use 64 ASCII characters that are compatible with all charset (latin1, utf8 …).

It avoids trashing the encrypted data by storing it in a mysql database or a mismatched file.