Php encryption/decryption examples

Source: Internet
Author: User
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 );
}

}

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.