1. 程式人生 > 實用技巧 >.NET實現AES加密解密

.NET實現AES加密解密

AES加密有五種密碼模式。.NET 內建的AES加密物件僅實現了兩種(CBC、ECB),如果要實現OFB、CFB、CTR加密,僅僅只靠.NET內建的AES加密物件就無法實現了。如果想要實現的話,可以依靠一款強大的.NET 加密庫:BouncyCastle.dll(nuget 上可找到 .NET Core版本:BouncyCastle.NetCore)。

今天作者向大家推薦的是一款依賴BouncyCastle.NetCore.dll實現加密的.NET 元件庫:ZHI.ZSystem。

相對於.NET內建AES加密物件,它有以下優勢:

  1.可以實現OFB、CFB、CTR、CTS加密

  2.靜態函式呼叫,操作簡單方便

相對於BouncyCastle加密庫,它有以下優勢:

  1.底層依賴BouncyCastle加密庫,bug少

  2.呼叫函式方式簡單,引數清晰明瞭,註釋齊全

接下來我們用程式碼來證明吧!

1.nuget 搜尋 ZHI.ZSystem並安裝(目標框架是.NET Standard 2.0,所以.NET Core 和 .NET Framework都可以下載並使用)

2.呼叫AES加密/解密方法。(真的超級簡單!)

3.得到結果。(下面我貼一下自己的加密結果)

介紹完了用法,擔心小夥伴們還是不太會用,所以把程式碼貼出來!

/// <summary>
/// 單元測試 記得引用ZHI.ZSystem庫
/// </summary> [Test] public void Test() { //AES KEY 128 BIT var aes_key = "dyoo9IaP1NbuMOwk"; //AES IV 16 BYTE var aes_iv = "kT0mtWAHg1lEympP"; // plaintext var plaintext = "嘿嘿嘿 $&*!"; //BASE64 輸出 var ciphertext_base_64_output = EncryptHelper.AESEncryptToBase64(plaintext, aes_key, aes_iv, AesCipherMode.CBC, AesPaddingMode.PKCS7Padding);
//Hex 輸出(十六進位制輸出) var ciphertext_hex_output = EncryptHelper.AESEncryptToHex(plaintext, aes_key, aes_iv, AesCipherMode.CBC, AesPaddingMode.PKCS7Padding); //AES 解密 BASE64 var base_64_decrypt = EncryptHelper.AESDecryptFromBase64(ciphertext_base_64_output, aes_key, aes_iv, AesCipherMode.CBC, AesPaddingMode.PKCS7Padding); //AES 解密 Hex var hex_decrypt = EncryptHelper.AESDecryptFromHex(ciphertext_hex_output, aes_key, aes_iv, AesCipherMode.CBC, AesPaddingMode.PKCS7Padding); Console.WriteLine("CBC密碼模式"); Console.WriteLine(" 加密結果base64輸出:{0}", ciphertext_base_64_output); Console.WriteLine(" 加密結果hex輸出:{0}", ciphertext_hex_output); Console.WriteLine(" 解密base64:{0}", base_64_decrypt); Console.WriteLine(" 解密hex:{0}", hex_decrypt); Console.WriteLine(); //BASE64 輸出 ciphertext_base_64_output = EncryptHelper.AESEncryptToBase64(plaintext, aes_key, aes_iv, AesCipherMode.CFB, AesPaddingMode.PKCS7Padding); //Hex 輸出(十六進位制輸出) ciphertext_hex_output = EncryptHelper.AESEncryptToHex(plaintext, aes_key, aes_iv, AesCipherMode.CFB, AesPaddingMode.PKCS7Padding); //AES 解密 BASE64 base_64_decrypt = EncryptHelper.AESDecryptFromBase64(ciphertext_base_64_output, aes_key, aes_iv, AesCipherMode.CFB, AesPaddingMode.PKCS7Padding); //AES 解密 Hex hex_decrypt = EncryptHelper.AESDecryptFromHex(ciphertext_hex_output, aes_key, aes_iv, AesCipherMode.CFB, AesPaddingMode.PKCS7Padding); Console.WriteLine("CFB密碼模式"); Console.WriteLine(" 加密結果base64輸出:{0}", ciphertext_base_64_output); Console.WriteLine(" 加密結果hex輸出:{0}", ciphertext_hex_output); Console.WriteLine(" 解密base64:{0}", base_64_decrypt); Console.WriteLine(" 解密hex:{0}", hex_decrypt); Console.WriteLine(); }

看完有沒有覺得特別簡單呢!