PhpAes encryption program code sharing _ PHP Tutorial

Source: Internet
Author: User
Tags mcrypt
PhpAes encryption program code sharing. Today it's okay with a PhpAes encryption program. if Yii extension is not needed in the Yii Framework () -replace params [encryptKey] with your corresponding default key. Today, it will be okay with a Php Aes encryption program. it is applicable to Yii extension. if you do not need to use Yii in the Yii Framework, set Yii in the code:: app ()-> params [\ 'encryption key \ '] can be replaced with your default key.

AES encryption algorithm-algorithm principle

The AES algorithm is based on the arrangement and replacement operations. Data arrangement is to reschedule data, and replacement is to replace one data unit with another. AES uses several different methods to perform the permutation and replacement operations.
AES is an iterative and symmetric key group password that uses 128, 192, and 256-bit keys and uses 128-bit (16-byte) groups to encrypt and decrypt data. Unlike the public key pair, the symmetric key uses the same key to encrypt and decrypt data. The number of digits of the encrypted data returned by the group password is the same as that of the input data. Iterative encryption uses a loop structure to repeatedly replace and replace input data in this loop.

The code is as follows:

/**
* Php AES encryption/decryption class
* Because java only supports 128-bit encryption, php also uses 128-bit encryption and can interoperate with java.
* At the same time, the AES standard is also 128 bits. Only the RIJNDAEL algorithm supports 128,192-bit and 256-bit encryption.
*
* @ Author Terry
*
*/
Class PhpAes
{
/**
* This was AES-128/CBC/ZeroBytePadding encrypted.
* Return base64_encode string
* @ Author Terry
* @ Param string $ plaintext
* @ Param string $ key
*/
Public static function AesEncrypt ($ plaintext, $ key = null)
{
If ($ plaintext = '') return '';
If (! Extension_loaded ('mcrypt '))
Throw new CException (Yii: t ('yii', 'aesencrypt requires PHP mcrypt extension to be loaded in order to use data encryption feature .'));
$ Size = mcrypt_get_block_size (MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC );
$ Plaintext = self: PKCS5Padding ($ plaintext, $ size );
$ Module = mcrypt_module_open (MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC ,'');
$ Key = self: substr ($ key = null? Yii: app ()-> params ['encryptkey']: $ key, 0, mcrypt_enc_get_key_size ($ module ));
/* Create the IV and determine the keysize length, use MCRYPT_RAND
* On Windows instead */
$ Iv = substr (md5 ($ key), 0, mcrypt_enc_get_iv_size ($ module ));
/* Intialize encryption */
Mcrypt_generic_init ($ module, $ key, $ iv );

/* Encrypt data */
$ Encrypted = mcrypt_generic ($ module, $ plaintext );

/* Terminate encryption handler */
Mcrypt_generic_deinit ($ module );
Mcrypt_module_close ($ module );
Return base64_encode (trim ($ encrypted ));
}

/**
* This was AES-128/CBC/ZeroBytePadding decrypted.
* @ Author Terry
* @ Param string $ encrypted base64_encode encrypted string
* @ Param string $ key
* @ Throws CException
* @ Return string
*/
Public static function AesDecrypt ($ encrypted, $ key = null)
{
If ($ encrypted = '') return '';
If (! Extension_loaded ('mcrypt '))
Throw new CException (Yii: t ('yii', 'aesdecrypt requires PHP mcrypt extension to be loaded in order to use data encryption feature .'));

$ Ciphertext_dec = base64_decode ($ encrypted );
$ Module = mcrypt_module_open (MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC ,'');
$ Key = self: substr ($ key = null? Yii: app ()-> params ['encryptkey']: $ key, 0, mcrypt_enc_get_key_size ($ module ));

$ Iv = substr (md5 ($ key), 0, mcrypt_enc_get_iv_size ($ module ));

/* Initialize encryption module for decryption */
Mcrypt_generic_init ($ module, $ key, $ iv );

/* Decrypt encrypted string */
$ Decrypted = mdecrypt_generic ($ module, $ ciphertext_dec );

/* Terminate decryption handle and close module */
Mcrypt_generic_deinit ($ module );
Mcrypt_module_close ($ module );
Return self: UnPKCS5Padding ($ decrypted );
}


Private static function strlen ($ string)
{
Return extension_loaded ('mbstring ')? Mb_strlen ($ string, '8bit '): strlen ($ string );
}

Private static function substr ($ string, $ start, $ length)
{
Return extension_loaded ('mbstring ')? Mb_substr ($ string, $ start, $ length, '8bit '): substr ($ string, $ start, $ length );
}

Private static function PKCS5Padding ($ text, $ blocksize ){
$ Pad = $ blocksize-(self: strlen ($ text) % $ blocksize );
Return $ text. str_repeat (chr ($ pad), $ pad );
}

Private static function UnPKCS5Padding ($ text)
{
$ Pad = ord ($ text {self: strlen ($ text)-1 });
If ($ pad> self: strlen ($ text) return false;
If (strspn ($ text, chr ($ pad), self: strlen ($ text)-$ pad )! = $ Pad) return false;
Return substr ($ text, 0,-1 * $ pad );
}
}

Usage

The code is as follows:

Require_once ('./AES. php ');
// $ Aes = new AES ();
$ Aes = new AES (true); // stores encrypted strings in hexadecimal format.
// $ Aes = new AES (true, true); // The encrypted string is stored in hexadecimal format with debugging information
$ Key = "this is a 32 byte key"; // key
$ Keys = $ aes-> makeKey ($ key );
$ Encode = "123456"; // encrypted string
$ Ct = $ aes-> encryptString ($ encode, $ keys );
Echo "encode =". $ ct ."
";
$ Cpt = $ aes-> decryptString ($ ct, $ keys );
Echo "decode =". $ cpt;
?>

Except Aes encryption program, applicable to Yii extension. if you do not need to use Yii Framework, put the Yii: app () in the code () -> replace params [\ 'encryption key \ '] with your default key...

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.