using System.Security.Cryptography;
AES可以直接调用
好像只有ECB CBC CFB可以直接用,CTR OFB不知道怎么用
static class MyAES { static PaddingMode[] padding = { PaddingMode.PKCS7, PaddingMode.ANSIX923, PaddingMode.ISO10126, PaddingMode.None, PaddingMode.Zeros };//这是填充方式 static public string Encrypt(string Message, string key, string IV, CipherMode Mode, int pad, int length) { // 明文 密钥 向量 加密模式 填充模式 密钥长度 try { //RijndaelManaged aes = new RijndaelManaged(); Rijndael aes = Rijndael.Create(); //aes.BlockSize = 128; //aes.FeedbackSize = 128; aes.KeySize = length; aes.Padding = padding[pad]; aes.Mode = Mode; //aes.Key = Encoding.UTF8.GetBytes(key); //aes.IV = Encoding.UTF8.GetBytes(IV); byte[] keyBytes = Encoding.UTF8.GetBytes(key); byte[] keyIV = Encoding.UTF8.GetBytes(IV); byte[] inputByteArray = Encoding.UTF8.GetBytes(Message); MemoryStream memStream = new MemoryStream(); CryptoStream crypStream = new CryptoStream(memStream, aes.CreateEncryptor(keyBytes, keyIV), CryptoStreamMode.Write); crypStream.Write(inputByteArray, 0, inputByteArray.Length); crypStream.FlushFinalBlock(); aes.Clear(); return Convert.ToBase64String(memStream.ToArray()); } catch { MessageBox.Show("加密失败"); return ""; } } //AES加密 static public string Decrypt(string Ciphertext, string key, string IV, CipherMode Mode, int pad, int length) { try { //RijndaelManaged aes = new RijndaelManaged(); Rijndael aes = Rijndael.Create(); //aes.BlockSize = 128; //aes.FeedbackSize = 128; //aes.Key = Encoding.UTF8.GetBytes(key); //aes.IV = Encoding.UTF8.GetBytes(IV); aes.KeySize = length; aes.Padding = padding[pad]; aes.Mode = Mode; byte[] keyBytes = Encoding.UTF8.GetBytes(key); byte[] keyIV = Encoding.UTF8.GetBytes(IV); byte[] outputByteArray = Convert.FromBase64String(Ciphertext); MemoryStream memStream = new MemoryStream(); CryptoStream crypStream = new CryptoStream(memStream, aes.CreateDecryptor(keyBytes, keyIV), CryptoStreamMode.Write); crypStream.Write(outputByteArray, 0, outputByteArray.Length); crypStream.FlushFinalBlock(); aes.Clear(); return Encoding.UTF8.GetString(memStream.ToArray()); } catch { MessageBox.Show("加密失败"); return ""; } } //AES解密 }
时间: 2024-10-10 07:51:31