c#加密-AES
/// <summary> /// aes加密 /// </summary> /// <param name="text"></param> /// <param name="key">秘钥</param> /// <param name="iv">偏移量</param> /// <returns></returns> public static string AESEncrypt(string text, string key, string iv) { RijndaelManaged rijndaelCipher = new RijndaelManaged(); rijndaelCipher.Mode = CipherMode.CBC; rijndaelCipher.Padding = PaddingMode.PKCS7; rijndaelCipher.KeySize = 128; rijndaelCipher.BlockSize = 128; byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(key); byte[] keyBytes = new byte[pwdBytes.Length]; int len = pwdBytes.Length; if (len > keyBytes.Length) len = keyBytes.Length; System.Array.Copy(pwdBytes, keyBytes, len); rijndaelCipher.Key = keyBytes; byte[] ivBytes = Encoding.UTF8.GetBytes(iv); rijndaelCipher.IV = ivBytes; ICryptoTransform transform = rijndaelCipher.CreateEncryptor(); byte[] plainText = Encoding.UTF8.GetBytes(text); byte[] cipherBytes = transform.TransformFinalBlock(plainText, 0, plainText.Length); //return Convert.ToBase64String(cipherBytes); return BitConverter.ToString(cipherBytes).Replace("-", ""); //return Encoding.GetString(cipherBytes); } /// <summary>AES解密</summary> /// <param name="text">ry密文</param> /// <param name="key">ry密钥,长度为16的字符串</param> /// <param name="iv">ry偏移量,长度为16的字符串</param> /// <returns>明文</returns> public static string AESDecrypt(string text, string key, string iv) { RijndaelManaged rijndaelCipher = new RijndaelManaged(); rijndaelCipher.Mode = CipherMode.CBC; rijndaelCipher.Padding = PaddingMode.PKCS7; rijndaelCipher.KeySize = 128; rijndaelCipher.BlockSize = 128; int count = text.Length / 2; string realText = string.Empty; for (int i = 0; i < count; i++) { string temp = text.Substring(2 * i, 2); realText += temp + "-"; } realText = realText.Remove(realText.Length - 1, 1); String[] arr = realText.Split('-'); byte[] encryptedData = new byte[arr.Length]; for (int i = 0; i < arr.Length; i++) encryptedData[i] = Convert.ToByte(arr[i], 16); //byte[] encryptedData = Convert.FromBase64String(text); //byte[] encryptedData = Encoding.UTF8.GetBytes(text); //byte[] encryptedData = Encoding.Default.GetBytes(text); //Encoding.Default.GetBytes(text); //ry--- byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(key); byte[] keyBytes = new byte[pwdBytes.Length]; int len = pwdBytes.Length; if (len > keyBytes.Length) len = keyBytes.Length; System.Array.Copy(pwdBytes, keyBytes, len); rijndaelCipher.Key = keyBytes; rijndaelCipher.IV = Encoding.UTF8.GetBytes(iv); ICryptoTransform transform = rijndaelCipher.CreateDecryptor(); byte[] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length); return Encoding.UTF8.GetString(plainText); }