Through the built-in functions of PHP, the _php technique of data encryption and decryption via DES algorithm

Source: Internet
Author: User
Tags decrypt getmessage mcrypt md5 asymmetric encryption
For project needs, write a class that generates an "Authorization Code" (The Authorization code mainly contains the expiration time used for the project), the generated authorization code will be written to a file that will automatically read the ciphertext in the file whenever the project runs, and then use a unique "key" to invoke a function to decrypt the ciphertext. read out the usage expiration time of the project.
Before, I have to try to write the first, mainly base64+md5+ inverted string. The algorithm is too simple, very easy to be cracked, and has not been able to do "key" in the encryption and decryption of the importance of it.
Later, the search for relevant information, found that the original PHP built-in a powerful function library, that is, MCrypt.
In fact, MCrypt itself provides a powerful encryption decryption method, and supports many popular public cryptographic 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 a simple reference to Baidu encyclopedia on the "Encryption algorithm" explanation:
The basic process of data encryption is to deal with a certain algorithm for files or data that were originally plaintext. Make it unreadable a piece of code, usually called "ciphertext", so that it can only enter the appropriate key to display the original content, through such a way to protect the data is not stolen by the illegal people, read the purpose. The reverse process of the process is the process of decrypting and converting the encoded information into its original data.
Encryption techniques are usually grouped into two broad categories: symmetric and asymmetric.
Symmetric encryption is the use of encryption and decryption of the same key, usually called "session Key" This encryption technology is currently widely used, such as the United States Government adopted DES Encryption standard is a typical "symmetric" encryption method, its session key length of 56Bits.
Asymmetric encryption is the encryption and decryption of the use of not the same key, usually has two keys, known as "Public Key" and "private key", they have two must pair use, otherwise cannot open the encrypted file. The "public key" here means that the "private key" can not be disclosed, and can only be known by the holder alone. Its superiority is here, because the symmetric encryption method if is transmits the encrypted file on the network to be able to send the key to the other party, regardless of method all may be not eavesdropping. The asymmetric encryption method has two keys, and the "public key" is open, it is not afraid of others know, the recipient decryption as long as the use of their own private key that can, so good to avoid the key transmission security issues.
As mentioned earlier, MCrypt supports a variety of internationally exposed algorithms, and I use the DES algorithm in this project, DES (Data encryption Standard), which is a symmetric algorithm that is faster and is suitable for encrypting large amounts of data.
Let me briefly explain a few of the functions that will be used in the encryption class.

--------------------------------------------------------------------------------
Resource Mcrypt_module_open (String $algorithm, String $algorithm _directory, String $mode, String $mode _directory)
Parameter $algorithm: The algorithm to use, you can view all supported algorithm names through function mcrypt_list_algorithms ()
Parameter $ mode: which mode to use, similarly, can be built-in function mcrypt_list_algorithms () to see all supported patterns

--------------------------------------------------------------------------------
int Mcrypt_enc_get_iv_size (Resource $td)
The function returns the size of the initialization vector (iv) of the algorithm used (looking somewhat abstract), and returns 0 if IV is ignored in the algorithm.
Parameter $TD is the return value using the Mcrypt_module_open function.

--------------------------------------------------------------------------------
String Mcrypt_create_iv (int $size [, int $source = Mcrypt_dev_random])
The function creates an initialization vector (IV)
Parameters:
$source can make mcrypt_rand,mcrypt_dev_random,
Mcrypt_dev_urandom
Note: PHP5.3.0 above version, only support Mcrypt_rand
return value:
succeeds, the initial vector of a string is returned, false if it fails

--------------------------------------------------------------------------------
int Mcrypt_enc_get_key_size (Resource $td)
The 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 the function, which can help us initialize the buffer for storing the encrypted data.
Parameter $key: Key length, remember that the value of the current $key is smaller than the value returned by the function mcrypt_enc_get_key_size ()
Question: $key value, the bigger the better? There are classmates, help answer.

--------------------------------------------------------------------------------
String Mcrypt_generic (Resource $td, string $data)
Once you have completed the previous work, you can call the function to encrypt the data.
Parameter $data: The content of the data to be encrypted
Return value: Returns the encrypted ciphertext

--------------------------------------------------------------------------------
BOOL Mcrypt_generic_deinit (Resource $TD)
This function can help us unload the encryption module currently in use.
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 it actually is, and there may be a subsequent one that needs to be removed

--------------------------------------------------------------------------------
BOOL Mcrypt_module_close (Resource $TD)
Closes the specified cryptographic module resource handle
return value
Returns TRUE on success or FALSE on failure.

--------------------------------------------------------------------------------
Put the code:
Copy Code code as follows:

<?php
Class Authcode {
Public $ttl//Expiration Time format: 20120101 (month-year date)
Public $key _1;//Key 1
Public $key _2;//Key 2
Public $td;
public $ks;//Length of key
public $iv;//Initial vector
public $salt;//salt value (a specific string)
public $encode;//Encrypted information
Public $return _array = Array (); Returns an array of strings with a MAC address
Public $mac _addr;//mac Address
Public $filepath//file path to save redaction
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 to improve the security of ciphertext
echo "<pre>". Print_r (Mcrypt_list_algorithms ()). " </pre> ";
echo "<pre>". Print_r (Mcrypt_list_modes ()). " </pre> ";
}
/**
* Encrypt plaintext information
* @param $key Key
*/
Public function encode ($key) {
$this->td = Mcrypt_module_open (Mcrypt_des, ', ' ECB ', '); Using the 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 an initial vector
$this->ks = mcrypt_enc_get_key_size ($this->td);//return 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
To save to plaintext
$con = $this->mac_addr. $this->ttl;
Encryption
$this->encode = mcrypt_generic ($this->td, $con);
End Processing
Mcrypt_generic_deinit ($this->td);
Save Redaction to a file
$this->savetofile ();
}
/**
* Decryption of ciphertext
* @param $key Key
*/
Public function decode ($key) {
try {
if (!file_exists ($this->filepath)) {
throw new Exception ("Authorization file does not exist");
}else{//read the ciphertext in the authorization file if the authorization file exists
$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 a subsequent, need to remove
$decrypted =trim ($decrypted). "\ n";
End
Mcrypt_generic_deinit ($this->td);
Mcrypt_module_close ($this->td);
return $decrypted;
}
}catch (Exception $e) {
echo $e->getmessage ();
}
}
/**
* Save Redaction to File
*/
Public Function SaveToFile () {
try {
$FP =fopen ($this->filepath, ' w+ ');
if (! $fp) {
throw new Exception ("File operation failed");
}
Fwrite ($fp, $this->encode);
Fclose ($FP);
}catch (Exception $e) {
echo $e->getmessage ();
}
}
/**
* Get the MAC address of the server
*/
Public Function Getmac ($os _type) {
Switch (Strtolower ($os _type)) {
Case "Linux":
$this->forlinux ();
Break
Case "Solaris":
Break
Case "UNIX":
Break
Case "AIX":
Break
Default
$this->forwindows ();
Break
}
$temp _array = Array ();
foreach ($this->return_array as $value) {
if (Preg_match ("/[0-9a-f][0-9a-f][:-]". " [0-9a-f] [0-9a-f] [:-]"." [0-9a-f] [0-9a-f] [:-]"." [0-9a-f] [0-9a-f] [:-]"." [0-9a-f] [0-9a-f] [:-]"." [0-9a-f] [0-9a-f]/i, $value, $temp _array)) {
$mac _addr = $temp _array[0];
Break
}
}
unset ($temp _array);
return $mac _addr;
}
/**
* Execute ipconfig command under Windows Server
*/
Public Function forwindows () {
@exec ("Ipconfig/all", $this->return_array);
if ($this->return_array)
return $this->return_array;
else{
$ipconfig = $_server["windir"]. " \system32\ipconfig.exe ";
if (Is_file ($ipconfig))
@exec ($ipconfig. "/all", $this->return_array);
Else
@exec ($_server["windir"]. " \system\ipconfig.exe/all ", $this->return_array);
return $this->return_array;
}
}
/**
* Execute ifconfig command under Linux Server
*/
Public Function Forlinux () {
@exec ("Ifconfig-a", $this->return_array);
return $this->return_array;
}
}
$code =new Authcode ();
Encryption
$code->encode ("~!@#$%^");
Decrypt
echo $code->decode ("~!@#$%^");
?>

Original article: Web Development _ Small Fly

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.