AES-CBC encryption and PHPC # implementation

Source: Internet
Author: User
I have been tossing for many days. Thanks to the help of jochu Daxia, we have finally completed AES.

I have been tossing for many days. Thanks to the help of jochu Daxia, I finally completed the AES-CBC encryption. I specially sorted out the encryption part and hoped to bring some help to future generations. [encryption specifications ]: encryption Standard: AES encryption algorithm: CBC BlockSize: 256bit (32 byte) keysize: 256 (32 byte) padding: pkcs7 AES-CBC is

I have been tossing for many days. Thanks to the help of jochu Daxia, I finally completed the AES-CBC encryption. I specially sorted out the encryption part, hoping to help future generations.

[Encryption specifications ]:

Encryption Standard: AES

Encryption Algorithm: CBC

BlockSize: 256bit (32 byte)

Keysize: 256 (32 byte)

Padding: pkcs7

AES-CBC is a method of segment decryption, that is, first segment the plain text, and then encryption, The Blocksize parameter defines the size of each segment, support 256 bit, after the segment, the last section may not be full of a blocksize, so you need to encrypt the plaintext in the encryption method. The pkcs7 method will be mentioned later. The key length can be 128, 192, or 256.

[Pkcs7]

The pkcs7 algorithm is actually relatively simple. You can encapsulate a function by yourself:

Step 1: Obtain the length of len and blocksize in bytes)

Part 2: Calculate the length of the last segment to be supplemented paddingLen = len-text % blocsize

Part 3: Get the character whose ASCII code is the length of paddingLen. Use this character to fill up the last segment. For details, see my PHP code.

PHP Encryption]

To use an encrypted function in PHP, you must install the mcrypt extension.

/*** Pkcs7 completion code ** @ param string $ string plaintext * @ param int $ blocksize Blocksize, in byte ** @ return String */function addPkcs7Padding ($ string, $ blocksize = 32) {$ len = strlen ($ string); // obtain the string length $ pad = $ blocksize-($ len % $ blocksize ); // get the length of the complement code $ string. = str_repeat (chr ($ pad), $ pad); // use the ASCII code to fill in the last return $ string ;} /*** encrypted and base64 transcoding ** @ param String plaintext * @ param encrypted initial vector (the IV length must be the same as Blocksize, and the same IV value must be used for encryption and decryption) * @ param $ key */function aes256cbcEncrypt ($ str, $ iv, $ key) {return base64_encode (mcrypt_encrypt (encrypt, $ key, addPkcs7Padding ($ str), MCRYPT_MODE_CBC, $ iv);}/*** remove pkcs7 padding ** @ param String the decrypted result ** @ return String */function stripPkcs7Padding ($ string) {$ slast = ord (substr ($ string,-1); $ slastc = chr ($ slast); $ pcheck = substr ($ string,-$ slast ); if (preg_match ("/$ slastc {". $ slast. "}/", $ string) {$ string = substr ($ string, 0, strlen ($ string)-$ slast); return $ string ;} else {return false ;}} /*** decrypt ** @ param String $ encryptedText binary ciphertext * @ param String $ iv IV iv * @ param String $ key ** @ return String */function aes256cbcDecrypt ($ encryptedText, $ iv, $ key) {$ encryptedText = base64_decode ($ encryptedText); return stripPkcs7Padding (mcrypt_decrypt (encrypt, $ key, $ encryptedText, encrypt, $ iv ));} $ e = aes256cbcEncrypt ("the dog pass through the street", '000000', '000000'); echo $ e ,"
"; Echo aes256cbcDecrypt ($ e, '000000', '000000 ');

[C # encryption]

C # relatively good built-in AES-CBC Encryption Class, only need using System. Security. Cryptography; on the line

        private String AES_encrypt(String Input, byte[] Iv, byte[] Key)        {            var aes = new RijndaelManaged();            aes.KeySize = 256;            aes.BlockSize = 256;            aes.Padding = PaddingMode.PKCS7;            aes.Key = Key;            aes.IV = Iv;            var encrypt = aes.CreateEncryptor(aes.Key, aes.IV);            byte[] xBuff = null;            using (var ms = new MemoryStream())            {                using (var cs = new CryptoStream(ms, encrypt, CryptoStreamMode.Write))                {                    byte[] xXml = Encoding.UTF8.GetBytes(Input);                    cs.Write(xXml, 0, xXml.Length);                }                xBuff = ms.ToArray();            }            String Output = Convert.ToBase64String(xBuff);            return Output;        }        private String AES_decrypt(String Input, byte[] Iv, byte[] Key)        {            RijndaelManaged aes = new RijndaelManaged();            aes.KeySize = 256;            aes.BlockSize = 256;            aes.Mode = CipherMode.CBC;            aes.Padding = PaddingMode.PKCS7;            aes.Key = Key;            aes.IV = Iv;            var decrypt = aes.CreateDecryptor();            byte[] xBuff = null;            using (var ms = new MemoryStream())            {                using (var cs = new CryptoStream(ms, decrypt, CryptoStreamMode.Write))                {                    byte[] xXml = Convert.FromBase64String(Input);                    cs.Write(xXml, 0, xXml.Length);                }                xBuff = ms.ToArray();            }            String Output = Encoding.UTF8.GetString(xBuff);            return Output;        }

Disclaimer: This article uses the CC BY-NC-SA 3.0 protocol for authorization

Reprinted, please indicate the source: Xiaojing's blog

Link: http://www.phpv5.com/blog/encrypt-aes-cbc

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.