php Encryption and Decryption Example Based on mcrypt

  • 2021-07-22 09:14:04
  • OfStack

This paper describes the encryption and decryption method of php based on mcrypt. Share it for your reference. The specific implementation method is as follows:

There are quite a few encryption methods in PHP, so let's look at the use of mcrypt extension. Also in the work need to use this thing to encrypt access to the user's Cookie value, carefully studied this aspect of the content.

1. Introduction

Mcrypt is an extension of PHP, which completes the encapsulation of common encryption algorithms. In fact, this extension is the encapsulation of mcrypt standard class library. mcrypt has completed quite a few commonly used encryption algorithms, such as DES, TripleDES, Blowfish (default), 3-WAY, SAFER-SK64, SAFER-SK128, TWOFISH, TEA, RC2 and GOST encryption algorithms, and provided four block encryption models of CBC, OFB, CFB and ECB.

2. Installation and use

To use this extension, you must first install the mcrypt standard class library, which can be downloaded from http://mcrypt. sourceforge. net. This extension is compiled and installed in the same way as the regular php extension and will not be described in detail.

3.4 Block Encryption Models

Mcrypt supports four block encryption models, which are briefly described as follows:

MCRYPT_MODE_ECB (electronic codebook) is suitable for encrypting a small amount of random data, such as encrypting the user's login password.

② MCRYPT_MODE_CBC (cipher block chaining) is suitable for important file types with high encryption security level.

③ MCRYPT_MODE_CFB (cipher feedback) is suitable for the situation where every byte of the data stream needs to be encrypted.

④ MCRYPT_MODE_OFB (output feedback, in 8bit) is compatible with CFB mode, but it is safer than CFB mode. The CFB mode causes error diffusion of encryption, and if one byte goes wrong, all subsequent byte go wrong. OFB mode does not have this problem. However, the security of this mode is not very high, so it is not recommended to use it.

⑤ MCRYPT_MODE_NOFB (ES90feedback, in nbit) and OFB are compatible, and the security is higher because of the block operation algorithm.

⑥ MCRYPT_MODE_STREAM is an additional model for stream encryption algorithms such as WAKE or RC4.

NOFB and STREAM are valid only if the version number of mycrypt is greater than or equal to libmcrypt-2. 4. x. (It's basically larger than this version now, and the latest major version of libmcrypt has reached 4.)

4. View supported algorithms and models

mcrypt_list_modes () Lists the models supported by the current environment

mcrypt_list_algorithms () Lists the algorithms supported in the current environment

For example, command line execution:

php -r "var_dump(mcrypt_list_modes()); var_dump(mcrypt_list_algorithms());"

You can list all the results.

5. How to use

Example 1:

<?php
$key = "this is a secret key";
$input = "Let us meet at 9 o'clock at the secret place.";
$encrypted_data = mcrypt_ecb (MCRYPT_3DES, $key, $input, MCRYPT_ENCRYPT);
?>

The simplest method is shown in Example 1. This method shows that $input is encrypted by using the algorithm of 3DES, and the encryption key is $key. However, the method called directly in this method has not been officially recommended, and it is also recommended that you do not use this method in development, and this method will not be used on a certain day. When calling in this way under php5, you can see an warning message, prompting "PHP Warning: attempt to use an empty IV, which is NOT recommend".

The officially recommended usage is shown in Example 2

Example 2:

<?php
    $key = "this is a secret key";
    $input = "Let us meet at 9 o'clock at the secret place.";
    // Open mcrypt , or mcrypt A resource object of type, which uses the ecb Pattern, using 3des As an encryption algorithm.
    $td = mcrypt_module_open('tripledes', '', 'ecb', '');
    // Create iv( Initialization vector )
    $iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
    // According to the key and iv Initialization $td, Complete initialization work such as memory allocation
    mcrypt_generic_init($td, $key, $iv);
    // Encrypt
    $encrypted_data = mcrypt_generic($td, $input);
    // Anti-initialization $td, Release resources
    mcrypt_generic_deinit($td);
    // Close the resource object and exit
     mcrypt_module_close($td);
?>

The above process completes the data encryption process. First, select the encryption algorithm and encryption mode to create the resource object of mcrypt and IV, then initialize the buffer (memory) required for encryption, then release buffer after encryption, and finally close the resource object.

The process of decryption is basically the same as that of encryption, as long as mcrypt_generic ($td, $input) is replaced by mdecrypt_generic ($td, $input), and other parts are exactly the same. Of course, for the symmetric encryption algorithm 3des, the key used for encryption and decryption must be exactly the same.

6. About IV

IV is not required in all models. IV is required for CFB and OFB, and CBC and EBC are optional. For a mode where IV is required, the values of the encrypted and decrypted IV must be identical, whereas CBC and EBC are not required. It can be the same or different, it doesn't matter.

7.1 Encryption and decryption classes with simple functions

class AMPCrypt {
    private static function getKey(){
        return md5('exampleKey');
     }
    public static function encrypt($value){
         $td = mcrypt_module_open('tripledes', '', 'ecb', '');
         $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_DEV_RANDOM);
         $key = substr(self::getKey(), 0, mcrypt_enc_get_key_size($td));
         mcrypt_generic_init($td, $key, $iv);
         $ret = base64_encode(mcrypt_generic($td, $value));
         mcrypt_generic_deinit($td);
         mcrypt_module_close($td);
        return $ret;
     }
    public static function dencrypt($value){
         $td = mcrypt_module_open('tripledes', '', 'ecb', '');
         $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_DEV_RANDOM);
         $key = substr(self::getKey(), 0, mcrypt_enc_get_key_size($td));
         $key = substr(self::getKey(), 0, mcrypt_enc_get_key_size($td));
         mcrypt_generic_init($td, $key, $iv);
         $ret = trim(mdecrypt_generic($td, base64_decode($value))) ;
         mcrypt_generic_deinit($td);
         mcrypt_module_close($td);
        return $ret;
     }
}

PS: About encryption technology, this site also provides the following encryption tools for your reference:

MD5 Online Encryption Tool: http://tools.ofstack.com/password/CreateMD5Password

Escape Encryption/Decryption Tool: http://tools.ofstack.com/password/escapepwd

Online SHA1 encryption tool: http://tools.ofstack.com/password/sha1encode

Short chain (short website) online generation tool: http://tools.ofstack.com/password/dwzcreate

Short chain (short website) online restoration tool: http://tools.ofstack.com/password/unshorturl

High strength cryptographic generator: http://tools.ofstack.com/password/CreateStrongPassword

I hope this article is helpful to everyone's PHP programming.


Related articles: