标签:CBC AES string C# aes Length combinedData new byte
1 public static string Decrypt(string combinedString, string keyString) 2 { 3 string plainText; 4 byte[] combinedData = Convert.FromBase64String(combinedString); 5 Aes aes = Aes.Create(); 6 aes.Key = Encoding.UTF8.GetBytes(keyString); 7 byte[] iv = new byte[aes.BlockSize / 8]; 8 byte[] cipherText = new byte[combinedData.Length - iv.Length]; 9 Array.Copy(combinedData, iv, iv.Length); 10 Array.Copy(combinedData, iv.Length, cipherText, 0, cipherText.Length); 11 aes.IV = iv; 12 aes.Mode = CipherMode.CBC; 13 ICryptoTransform decipher = aes.CreateDecryptor(aes.Key, aes.IV); 14 15 using (MemoryStream ms = new MemoryStream(cipherText)) 16 { 17 using (CryptoStream cs = new CryptoStream(ms, decipher, CryptoStreamMode.Read)) 18 { 19 using (StreamReader sr = new StreamReader(cs)) 20 { 21 plainText = sr.ReadToEnd(); 22 } 23 } 24 25 return plainText; 26 } 27 } 28 29 public static string Encrypt(string plainText, string keyString) 30 { 31 byte[] cipherData; 32 Aes aes = Aes.Create(); 33 aes.Key = Encoding.UTF8.GetBytes(keyString); 34 aes.GenerateIV(); 35 aes.Mode = CipherMode.CBC; 36 ICryptoTransform cipher = aes.CreateEncryptor(aes.Key, aes.IV); 37 38 using (MemoryStream ms = new MemoryStream()) 39 { 40 using (CryptoStream cs = new CryptoStream(ms, cipher, CryptoStreamMode.Write)) 41 { 42 using (StreamWriter sw = new StreamWriter(cs)) 43 { 44 sw.Write(plainText); 45 } 46 } 47 48 cipherData = ms.ToArray(); 49 } 50 51 byte[] combinedData = new byte[aes.IV.Length + cipherData.Length]; 52 Array.Copy(aes.IV, 0, combinedData, 0, aes.IV.Length); 53 Array.Copy(cipherData, 0, combinedData, aes.IV.Length, cipherData.Length); 54 return Convert.ToBase64String(combinedData); 55 }
搜索
复制
标签:CBC,AES,string,C#,aes,Length,combinedData,new,byte 来源: https://www.cnblogs.com/dongzhaosheng/p/16315741.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。