Home  >  Article  >  Backend Development  >  Encrypt and decrypt data through DES algorithm through PHP's built-in functions_PHP tutorial

Encrypt and decrypt data through DES algorithm through PHP's built-in functions_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:18:36844browse

Due to the needs of the project, it is necessary to write a class that can generate an "authorization code" (the authorization code mainly contains the expiration time of the project). The generated authorization code will be written to a file. Whenever the project is run, it will Automatically read the ciphertext in the file, and then use the unique "key" to call a function to decrypt the ciphertext and interpret the expiration time of the project.
Before, I tried to write it myself, mainly base64+md5+reverse string. The algorithm is too simple and can be easily cracked, and it fails to realize the importance of the "key" in encryption and decryption, so it is abandoned.
Later, I searched for relevant information and found that there is a powerful function library built into PHP, namely Mcrypt.
In fact, mcrypt itself provides powerful encryption and decryption methods, and supports many popular public encryption algorithms, such as DES, TripleDES, Blowfish (default), 3-WAY, SAFER-SK64, SAFER-SK128, TWOFISH, TEA, RC2 and GOST in CBC, OFB, CFB and ECB.
Here is a simple quote from Baidu Encyclopedia’s explanation of “encryption algorithm”:
The basic process of data encryption is to process files or data that were originally plain text according to a certain algorithm, making it an unreadable piece of code. , usually called "ciphertext", so that the original content can only be displayed after entering the corresponding key. In this way, the purpose of protecting the data from being stolen and read by illegal persons is achieved. The reverse of this process is decryption, the process of converting the encoded information into its original data.
Encryption technologies are usually divided into two categories: "symmetric" and "asymmetric".
Symmetric encryption means that encryption and decryption use the same key, usually called "Session Key". This encryption technology is currently widely used. For example, the DES encryption standard adopted by the US government is a typical "symmetric encryption". "Encryption method, its Session Key length is 56Bits.
Asymmetric encryption means that encryption and decryption use different keys. There are usually two keys, called "public key" and "private key". They must be paired together, otherwise the encryption cannot be opened. document. The "public key" here means that it can be disclosed to the outside world, but the "private key" cannot, and can only be known by the holder. Its superiority lies here, because if the symmetric encryption method is transmitting encrypted files on the network, it will be difficult to tell the other party the key, and it may be eavesdropped no matter what method is used. The asymmetric encryption method has two keys, and the "public key" can be made public, so there is no fear of others knowing. The recipient only needs to use his own private key when decrypting, which is very good. This avoids key transmission security issues.
As mentioned earlier, mcrypt supports a variety of internationally public algorithms. In this project, I used the DES algorithm, DES (Data Encryption Standard), which is a symmetric algorithm, fast and suitable for encryption. Large amounts of data.
Next, I will briefly explain several functions used in the encryption class.

-------------------------------------------------- ------------------------------------
resource mcrypt_module_open ( string $algorithm , string $algorithm_directory , string $mode , string $mode_directory )
Parameter $algorithm: the algorithm to be used, you can view all supported algorithm names through the function mcrypt_list_algorithms()
Parameter $mode: which mode to use, similarly, can be built-in Function mcrypt_list_algorithms() to view all supported modes

---------------------------------- -----------------------------------------------
int mcrypt_enc_get_iv_size ( resource $td )
This function will return the size of the initialization vector (IV) of the algorithm used (it looks a bit abstract), and returns 0 if the IV is ignored in the algorithm.
The parameter $td is the return value of the mcrypt_module_open function.

-------------------------------------------------- ------------------------------------
string mcrypt_create_iv ( int $size [, int $source = MCRYPT_DEV_RANDOM ] )
This function will create an initialization vector (IV)
Parameters:
$source can be MCRYPT_RAND, MCRYPT_DEV_RANDOM,
MCRYPT_DEV_URANDOM
Note: PHP5.3.0 or above, only Supports MCRYPT_RAND
Return value:
If successful, a string initial vector will be returned. If failed, False will be returned.

---------------- -------------------------------------------------- -------------
int mcrypt_enc_get_key_size ( resource $td )
This function can obtain the maximum key length (in bytes) supported by the current algorithm
int mcrypt_generic_init ( resource $td , string $key , string $iv )
Before calling mcrypt_generic() or mdecrypt_generic(), you first need to call this function. This function can help us initialize the buffer to store encrypted data.
Parameter $key: key length. Remember, the current value of $key is smaller than the value returned by the function mcrypt_enc_get_key_size()
Question: Is the larger the value of $key, the better? If there is a classmate association, please help me answer this question.

-------------------------------------------------- ------------------------------------
string mcrypt_generic ( resource $td , string $data )
After completing the previous work, you can call this function to encrypt the data.
Parameter $data: the data content to be encrypted
Return value: return the encrypted ciphertext

-------------------------- -------------------------------------------------- ----------
bool mcrypt_generic_deinit ( resource $td )
This function can help us uninstall the currently used encryption module.
Return Value
Returns TRUE on success, or FALSE on failure.

------------------------ -------------------------------------------------- ------
string mdecrypt_generic ( resource $td , string $data )
This function can be used to decrypt data.
Note: The decrypted data may be longer than the actual one, and there may be subsequent


class authCode {
public $ttl;//Expiration time time format: 20120101 (year, month, day)
public $key_1;//Key 1
public $key_2;//Key 2
public $td;
public $ks;//The length of the key
public $iv;//Initial vector
public $salt;/ /Salt value (a specific string)
public $encode;//Encrypted information
public $return_array = array(); // Returns a string array with MAC address
public $mac_addr;//mac address
public $filepath;//file path to save ciphertext
public function __construct(){
//Get physical address
$this->mac_addr=$ this->getmac(PHP_OS);
$this->filepath="./licence.txt";
$this->ttl="20120619";//Expiration time
$ this->salt="~!@#$";//Salt value, used to improve the security of ciphertext
// echo "
".print_r(mcrypt_list_algorithms ())."< /pre>"; <br>// echo "<pre class="brush:php;toolbar:false">".print_r(mcrypt_list_modes())."
";
}
/**
* Encrypt plain text information
* @param $key key
*/
public function encode($key) {
$this->td = mcrypt_module_open(MCRYPT_DES,'','ecb',''); //Use MCRYPT_DES algorithm, ecb mode
$size=mcrypt_enc_get_iv_size( $this->td);//Set the size of the initial vector
$this->iv = mcrypt_create_iv($size, MCRYPT_RAND);//Create the initial vector
$this->ks = mcrypt_enc_get_key_size( $this->td);//Returns the maximum supported key length (in bytes)
$this->key_1 = substr(md5(md5($key).$this-> salt),0,$this->ks);
mcrypt_generic_init($this->td, $this->key_1, $this->iv); //Initial processing
//Required Save to plain text
$con=$this->mac_addr.$this->ttl;
//Encryption
$this->encode = mcrypt_generic($this->td, $con );
//End processing
mcrypt_generic_deinit($this->td);
//Save the ciphertext to the file
$this->savetofile();
}
/**
* Decrypt the ciphertext
* @param $key key
*/
public function decode($key) {
try {
if (!file_exists($this->filepath)){
throw new Exception ("Authorization file does not exist");
}else{//If the authorization file exists, read the ciphertext in the authorization file
$fp=fopen($this->filepath,'r' );
$secret=fread($fp,filesize($this->filepath));
$this->key_2 = substr(md5(md5($key).$this->salt ),0,$this->ks);
//Initial decryption processing
mcrypt_generic_init($this->td, $this->key_2, $this->iv);
//Decrypt
$decrypted = mdecrypt_generic($this->td, $secret);
//After decryption, there may be subsequent
Original article: WEB development_Xiao Fei

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/325532.htmlTechArticleDue to the needs of the project, it is necessary to write a class that can generate an "authorization code" (the authorization code mainly includes the Expiration time), the generated authorization code will be written to a file, whenever...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn