Encryption and decryption are common tasks. here we will introduce an encryption and decryption class. If you want to retrieve the original password when the user forgets the password, this class is a useful tool. the password registered by the user is generally not saved in plain text, so you must add a password first. The simplest of course is to call the md5 function in the Database SQL statement to encrypt the user password. Here is an encryption/decryption class. If you want to retrieve the original password when the user forgets the password, this class is a useful tool. Of course, this encryption/decryption class can also be used for other purposes.
The code is as follows:
Class crypt {
Private $ skey;
Public function _ construct ($ key ){
$ This-> skey = hash ("md5", $ key, true); // 32-bit skey
}
Public function safe_b64encode ($ string ){
$ Data = base64_encode ($ string );
$ Data = str_replace (array ('+', '/', '='), array ('-', '_', ''), $ data );
Return $ data;
}
Public function safe_b64decode ($ string ){
$ Data = str_replace (array ('-', '_'), array ('+', '/'), $ string );
$ Mod4 = strlen ($ data) % 4;
If ($ mod4 ){
$ Data. = substr ('====', $ mod4 );
}
Return base64_decode ($ data );
}
Public function encode ($ value ){
If (! $ Value ){
Return false;
}
$ Text = $ value;
$ Iv_size = mcrypt_get_iv_size (MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB );
$ Iv = mcrypt_create_iv ($ iv_size, MCRYPT_RAND );
$ Crypttext = mcrypt_encrypt (MCRYPT_RIJNDAEL_256, $ this-> skey, $ text, MCRYPT_MODE_ECB, $ iv );
Return trim ($ this-> safe_b64encode ($ crypttext ));
}
Public function decode ($ value ){
If (! $ Value ){
Return false;
}
$ Crypttext = $ this-> safe_b64decode ($ value );
$ Iv_size = mcrypt_get_iv_size (MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB );
$ Iv = mcrypt_create_iv ($ iv_size, MCRYPT_RAND );
$ Decrypttext = mcrypt_decrypt (MCRYPT_RIJNDAEL_256, $ this-> skey, $ crypttext, MCRYPT_MODE_ECB, $ iv );
Return trim ($ decrypttext );
}
}