C# AES,AesManaged使用學習

來源:互聯網
上載者:User

標籤:style   blog   http   color   使用   os   io   for   

加密

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;        }

解密

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();        }

示範:

string str = "Test ase,我們一起來測試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("明文:{0}", str);                Console.WriteLine("明文數組:{0}", FormatBytes(plainBytes));                Console.WriteLine("加密後的數組:{0}", FormatBytes(eBytes));                Console.WriteLine("解密後的數組:{0}", FormatBytes(dBytes));                Console.WriteLine("解密的明文:{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();        }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.