C # learning how to use AES and aesmanaged

Source: Internet
Author: User

Encryption

static byte[] EncryptBytes_Aes(byte[] plainText, byte[] Key, byte[] IV)        {            // Check arguments.            if (plainText == null || plainText.Length <= 0)                throw new ArgumentNullException("plainText");            if (Key == null || Key.Length <= 0)                throw new ArgumentNullException("Key");            if (IV == null || IV.Length <= 0)                throw new ArgumentNullException("IV");            byte[] encrypted;            // Create an AesManaged object            // with the specified key and IV.            using (AesManaged aesAlg = new AesManaged())            {                aesAlg.Key = Key;                aesAlg.IV = IV;                // Create a decrytor to perform the stream transform.                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);                // Create the streams used for encryption.                using (MemoryStream msEncrypt = new MemoryStream())                {                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))                    {                        using (BinaryWriter bw = new BinaryWriter(csEncrypt))                        {                            bw.Write(plainText);                        }                    }                    encrypted = msEncrypt.ToArray();                }            }            // Return the encrypted bytes from the memory stream.            return encrypted;        }

Decryption

static byte[] DecryptBytes_Aes(byte[] cipherText, byte[] Key, byte[] IV)        {            // Check arguments.            if (cipherText == null || cipherText.Length <= 0)                throw new ArgumentNullException("cipherText");            if (Key == null || Key.Length <= 0)                throw new ArgumentNullException("Key");            if (IV == null || IV.Length <= 0)                throw new ArgumentNullException("IV");            // Declare the string used to hold            // the decrypted text.            List<byte> plaintext = new List<byte>();            // Create an AesManaged object            // with the specified key and IV.            using (AesManaged aesAlg = new AesManaged())            {                aesAlg.Key = Key;                aesAlg.IV = IV;                // Create a decrytor to perform the stream transform.                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);                // Create the streams used for decryption.                using (MemoryStream msDecrypt = new MemoryStream(cipherText))                {                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))                    {                        using (BinaryReader br = new BinaryReader(csDecrypt))                        {                            int bufferLen = 1024;                            byte[] buffer = new byte[bufferLen];                            int read = 0;                            while ((read = br.Read(buffer, 0, bufferLen)) > 0)                                plaintext.AddRange(buffer.Take(read));                        }                    }                }            }            return plaintext.ToArray();        }

Demo:

String STR = "test ase, let's test AES"; byte [] plainbytes = encoding. utf8.getbytes (STR); Using (aesmanaged AES = new aesmanaged () {byte [] ebytes = encryptbytes_aes (plainbytes, AES. key, AES. IV); byte [] dbytes = decryptbytes_aes (ebytes, AES. key, AES. IV); // outputbytes (plainbytes); // outputbytes (ebytes); // outputbytes (dbytes); console. writeline ("plaintext: {0}", STR); console. writeline ("plaintext array: {0}", formatbytes (plainbytes); console. writeline ("encrypted array: {0}", formatbytes (ebytes); console. writeline ("decrypted array: {0}", formatbytes (dbytes); console. writeline ("decrypted plaintext: {0}", encoding. utf8.getstring (dbytes ));}
static string FormatBytes(byte[] bytes,byte countInLine = 10)        {            StringBuilder sb = new StringBuilder();            int i = 0;            foreach (byte b in bytes)            {                if (i++ % countInLine == 0)                    sb.Append(‘\n‘);                sb.Append(String.Format("{0:X2}  ", b));            }            sb.Append(‘\b‘);            return sb.ToString();        }

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.