對稱加密:就是采用這種加密方法的雙方使用方式用同樣的密鑰進行加密和解密。密鑰是控制加密及解密過程的指令。算法是一組規則,規定如何進行加密和解密。
因此加密的安全性不僅取決於加密算法本身,密鑰管理的安全性更是重要。因為加密和解密都使用同一個密鑰,如何把密鑰安全地傳遞到解密者手上就成了必須要解決的問題。
由此可見密鑰傳遞也是比較重要的一環,一般都是通過對密鑰二次加密的方式,進行密鑰的傳輸
加密實現代碼:
- public static byte[] encryptStringToBytes_AES(byte[] fileContentBytes, byte[] Key, byte[] IV)
- {
- // Check arguments.
- if (fileContentBytes == null || fileContentBytes.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");
- MemoryStream msEncrypt = null;
- AesCryptoServiceProvider aesAlg = null;
- try
- {
- aesAlg = new AesCryptoServiceProvider();
- aesAlg.Padding = PaddingMode.PKCS7;
- aesAlg.Key = Key;
- aesAlg.IV = IV;
- ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
- msEncrypt = new MemoryStream();
- using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
- {
- csEncrypt.Write(fileContentBytes, 0, fileContentBytes.Length);
- csEncrypt.FlushFinalBlock();
- }
- }
- catch (Exception ex)
- {
- }
- finally
- {
- if (aesAlg != null)
- aesAlg.Clear();
- }
- return msEncrypt.ToArray();
- }
解密代碼實現:
- public static byte[] decryptBytes(byte[] cipherText, byte[] Key, byte[] IV)
- {
- 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");
- AesCryptoServiceProvider aesAlg = null;
- byte[] buffer = null;
- try
- {
- using (aesAlg = new AesCryptoServiceProvider())
- {
- aesAlg.Padding = PaddingMode.PKCS7;
- aesAlg.Key = Key;
- aesAlg.IV = IV;
- ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
- using (MemoryStream msDecrypt = new MemoryStream(cipherText))
- {
- CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);
- byte[] tempbuffer = new byte[cipherText.Length];
- int totalBytesRead = csDecrypt.Read(tempbuffer, 0, tempbuffer.Length);
- buffer = tempbuffer.Take(totalBytesRead).ToArray();
- }
- }
- }
- catch (Exception ex)
- {
- }
- finally
- {
- if (aesAlg != null)
- aesAlg.Clear();
- }
- return buffer;
- }
客戶端加密解密文本文件實戰:
- /// <summary>
- /// 加密解密
- /// </summary>
- private static void _EncryptAndDecrypt()
- {
- ASCIIEncoding asciiEnc = new ASCIIEncoding();
- byte[] initVe