PHP Security Basics Appendix C. Encryption

Source: Internet
Author: User
Tags crypt mcrypt

Appendix C. Encryption

As a security-related book, encryption is usually a topic to be mentioned. The reason why I ignore encryption in the main part of this book is that it is used in a narrow sense, and developers should focus on security issues. Over-reliance on encryption often confuses the root cause of the problem. Although encryption is effective, encryption does not magically improve the security of an application.

A PHP developer should be familiar with the following encryption methods:

 

L symmetric encryption

L asymmetric encryption (Public Key)

L hash function (Information summary)

L Information Verification Code

 

This appendix focuses on symmetric encryption using mcrypt extensionsAlgorithm. You need to refer to the following materials:

 

Applied cryptography, by Bruce Schneier (Wiley)

Http://www.schneier.com/blog/

Http://wikipedia.org/wiki/Cryptography

Http://phpsec.org/articles/2005/password-hashing.html

Http://pear.php.net/package/Crypt_HMAC

Http://pear.php.net/package/Crypt_RSA

 

C.1. Password Storage

When you store a password in a database, you should never store it in plaintext mode. Instead, you should store the hash value of the password and use additional strings at the same time:

 

<? PHP

 

/* $ Password contains the password .*/

 

$ Salt = 'shiflett ';

$ Password_hash = MD5 ($ salt. MD5 ($ password. $ salt ));

 

/* Store password hash .*/

 

?>

 

When you need to confirm whether a password is correct, calculate the hash value in the same way and compare the Similarities and Differences:

 

<? PHP

 

$ Salt = 'shiflett ';

$ Password_hash = MD5 ($ salt. MD5 ($ _ post ['Password']. $ salt ));

 

/* Compare password hashes .*/

 

?>

 

If the hash value is the same, you have reason to think that the password is the same.

If this technique is used, it is impossible to tell the user what their password is. When a user forgets the password, you can only ask him to enter a new password and re-calculate the hash value and save it to the database. Of course, you need to be very careful with the user's identity confirmation-the password reminder mechanism is vulnerable to frequent attacks and is also the source of frequent security vulnerabilities.

 

C.2. use mcrypt

The standard encryption extension of PHP is mcrypt, which supports many different encryption algorithms. You can use the mcrypt_list_algorithms () function to view the list of Algorithms supported on your platform:

 

<? PHP

 

Echo '<PRE>'. print_r (mcrypt_list_algorithms (), true). '</PRE> ';

 

?>

 

Encryption and decryption are implemented by the mcrypt_encrypt () and mcrypt_decrypt () functions. Both functions have five parameters. The first parameter is used to specify the algorithm used:

 

<? PHP

 

Mcrypt_encrypt ($ algorithm,

$ Key,

$ Cleartext,

$ Mode,

$ IV );

 

Mcrypt_decrypt ($ algorithm,

$ Key,

$ Ciphertext,

$ Mode,

$ IV );

 

?>

 

The encryption key (the second parameter) is very sensitive data, so make sure that it is stored in a safe place. You can use the method of protecting database permissions in Chapter 8 to protect the encryption key. If economic conditions permit, the hardware encryption key is the best choice, providing super powerful security.

The function has multiple modes to choose from. You can use mcrypt_list_modes () to list all supported modes:

<? PHP

 

Echo '<PRE>'. print_r (mcrypt_list_modes (), true). '</PRE> ';

 

?>

 

The fifth parameter ($ IV) is the initialization vector, which can be created using the mcrypt_create_iv () function.

The following example provides the basic encryption and decryption methods:

 

Class crypt

{

Private $ algorithm;

Private $ mode;

Private $ random_source;

 

Public $ cleartext;

Public $ ciphertext;

Public $ IV;

 

Public Function _ construct ($ algorithm = mcrypt_blowfish,

$ Mode = mcrypt_mode_cbc,

$ Random_source = mcrypt_dev_urandom)

{

$ This-> algorithm = $ algorithm;

$ This-> mode = $ mode;

$ This-> random_source = $ random_source;

}

 

Public Function generate_iv ()

{

$ This-> IV = mcrypt_create_iv (mcrypt_get_iv_size ($ this-> algorithm,

$ This-> mode), $ this-> random_source );

}

 

Public Function encrypt ()

{

$ This-> ciphertext = mcrypt_encrypt ($ this-> algorithm,

$ _ Server ['crypt _ key'], $ this-> cleartext, $ this-> mode, $ this-> IV );

}

 

Public Function decrypt ()

{

$ This-> cleartext = mcrypt_decrypt ($ this-> algorithm,

$ _ Server ['crypt _ key'], $ this-> ciphertext, $ this-> mode, $ this-> IV );

}

}

 

?>

 

The above class will be used in other examples. Below is an example of its usage:

 

<? PHP

 

$ Crypt = new crypt ();

 

$ Crypt-> cleartext = 'this is a string ';

$ Crypt-> generate_iv ();

$ Crypt-> encrypt ();

 

$ Ciphertext = base64_encode ($ crypt-> ciphertext );

$ IV = base64_encode ($ crypt-> IV );

 

Unset ($ crypt );

 

/* Store $ ciphertext and $ IV (initialization vector ).*/

 

$ Ciphertext = base64_decode ($ ciphertext );

$ IV = base64_decode ($ IV );

 

$ Crypt = new crypt ();

 

$ Crypt-> IV = $ IV;

$ Crypt-> ciphertext = $ ciphertext;

$ Crypt-> decrypt ();

 

$ Cleartext = $ crypt-> cleartext;

 

?>

 

Tips

This extension requires you to use the-mcrypt identifier when compiling PHP. For the installation guide and requirements, see http://php.net/mcrypt.

 

C.3. saving credit card numbers

I am often asked how to save my credit card number safely. I always first ask them if they really need to save the credit card number. After all, it is unwise to introduce unnecessary risks no matter how they are operated. At the same time, there are also national laws and regulations on credit card information processing, and I am always reminded with caution that I am not a legal expert.

In this book, I will not specifically discuss how to deal with credit card processing, but will explain how to save encrypted information to the database and decrypt it during reading. This process may lead to a reduction in system performance, but does provide a protection measure. The main advantage is that if the database content leaks, only encrypted information is exposed, but the premise is that the encryption key is secure. Therefore, encryption keys and encryption implementation methods are equally important.

The process of saving encrypted data to the data is to encrypt the data first, and then establish a secret with the plaintext through the initial vector to save it to the database. Because ciphertext is a binary string, base64_encode () must be used to convert it into a common text string to ensure safe storage of binary encoding.

 

<? PHP

 

$ Crypt = new crypt ();

 

$ Crypt-> cleartext = '20140901 ';

$ Crypt-> generate_iv ();

$ Crypt-> encrypt ();

 

$ Ciphertext = $ crypt-> ciphertext;

$ IV = $ crypt-> IV;

 

$ String = base64_encode ($ IV. $ ciphertext );

 

?>

 

Save the string to the database. When reading, it is the inverse processing of the above process:

 

<? PHP

 

$ String = base64_decode ($ string );

 

$ Iv_size = mcrypt_get_iv_size ($ algorithm, $ mode );

 

$ Ciphertext = substr ($ string, $ iv_size );

$ IV = substr ($ string, 0, $ iv_size );

 

$ Crypt = new crypt ();

 

$ Crypt-> IV = $ IV;

$ Crypt-> ciphertext = $ ciphertext;

$ Crypt-> decrypt ();

 

$ Cleartext = $ crypt-> cleartext;

 

?>

 

This implementation method assumes that the encryption algorithm and mode remain unchanged. If they are not, you need to save them for data decryption. The encryption key is the only data that requires confidentiality.

 

C.4. encrypt session data

If your database has security issues or some data stored in the session is sensitive, you may want to encrypt the session data. Unless necessary, I do not recommend this method. However, if you think this is required in your case, this section provides an example of the implementation method.

This solution is very simple. In fact, Chapter 8 describes how to execute your own session mechanism by calling session_set_save_handler. With a few adjustments to the function for saving and reading data, you can encrypt the data stored in the database and decrypt the data when reading:

 

<? PHP

 

Function _ read ($ id)

{

Global $ _ sess_db;

 

$ Algorithm = mcrypt_blowfish;

$ Mode = mcrypt_mode_cbc;

 

$ Id = mysql_real_escape_string ($ id );

 

$ SQL = "Select data

From sessions

Where id = '$ id '";

 

If ($ result = mysql_query ($ SQL, $ _ sess_db ))

{

$ Record = mysql_fetch_assoc ($ result );

 

$ DATA = base64_decode ($ record ['data']);

 

$ Iv_size = mcrypt_get_iv_size ($ algorithm, $ mode );

 

$ Ciphertext = substr ($ data, $ iv_size );

$ IV = substr ($ data, 0, $ iv_size );

 

$ Crypt = new crypt ();

 

$ Crypt-> IV = $ IV;

$ Crypt-> ciphertext = $ ciphertext;

$ Crypt-> decrypt ();

 

Return $ crypt-> cleartext;

}

 

Return '';

}

 

Function _ write ($ id, $ data)

{

Global $ _ sess_db;

 

$ Access = Time ();

 

$ Crypt = new crypt ();

 

$ Crypt-> cleartext = $ data;

$ Crypt-> generate_iv ();

$ Crypt-> encrypt ();

 

$ Ciphertext = $ crypt-> ciphertext;

$ IV = $ crypt-> IV;

 

$ DATA = base64_encode ($ IV. $ ciphertext );

 

$ Id = mysql_real_escape_string ($ id );

$ Access = mysql_real_escape_string ($ access );

$ DATA = mysql_real_escape_string ($ data );

 

$ SQL = "replace

Into sessions

Values ('$ id',' $ access', '$ data ')";

 

Return mysql_query ($ SQL, $ _ sess_db );

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.