AES解密中FlushFinalBlock遇到的错误 解决方案 和疑问

我想using System.Security.Cryptography;实现AES的加密解密功能,加密可以正常进行

解密时红色地方的语句会出现异常。

 

 

如果算法用的DES就没这个问题,请问这个异常怎么解决,微软官方上都没解决方案,国外一些提问网站也没解决。不知道谁能告诉我怎么做

 

 //AES加密
        public static string EnAES(string str, string encryptKey, string encryptVector)
        {

            int keySize = encryptKey.Length * 8;
            AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
            if (aes.ValidKeySize(keySize) == false)
            {
                keySize = Convert.ToInt32(aes.LegalKeySizes[0].MaxSize);
                if (keySize / 8 > encryptKey.Length)
                    encryptKey = encryptKey.PadRight(keySize / 8, '0');
                else
                    encryptKey = encryptKey.Substring(0, keySize / 8);
            }
            if (aes.BlockSize / 8 > encryptVector.Length)
                encryptVector = encryptVector.PadRight(aes.BlockSize / 8, '0');
            else
                encryptVector = encryptVector.Substring(0, aes.BlockSize / 8);

            byte[] key = Encoding.ASCII.GetBytes(encryptKey);
            byte[] data = Encoding.Unicode.GetBytes(str);
            byte[] vector = Encoding.ASCII.GetBytes(encryptVector);
            System.IO.MemoryStream MStream = new System.IO.MemoryStream();
            CryptoStream CStream = new CryptoStream(MStream, aes.CreateEncryptor(key, vector), CryptoStreamMode.Write);
            CStream.Write(data, 0, data.Length);
            CStream.FlushFinalBlock();
            return Convert.ToBase64String(MStream.ToArray());
        }

        //AES解密
        public static string DeAES(string str, string encryptKey, string encryptVector)
        {
            int keySize = encryptKey.Length * 8;
            AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
            if (aes.ValidKeySize(keySize) == false)
            {
                keySize = Convert.ToInt32(aes.LegalKeySizes[0].MaxSize);
                if (keySize / 8 > encryptKey.Length)
                    encryptKey = encryptKey.PadRight(keySize / 8, '0');
                else
                    encryptKey = encryptKey.Substring(0, keySize / 8);
            }
            if (aes.BlockSize / 8 > encryptVector.Length)
                encryptVector = encryptVector.PadRight(aes.BlockSize / 8, '0');
            else
                encryptVector = encryptVector.Substring(0, aes.BlockSize / 8);
            byte[] key = Encoding.ASCII.GetBytes(encryptKey);
            byte[] data = Encoding.Unicode.GetBytes(str);
            byte[] vector = Encoding.ASCII.GetBytes(encryptVector);

 

 

 

            System.IO.MemoryStream MStream = new System.IO.MemoryStream(data.Length+256);
            CryptoStream CStream = new CryptoStream(MStream, aes.CreateDecryptor(key, vector), CryptoStreamMode.Write);

            CStream.Write(data, 0, data.Length);
            //出exception的语句
            CStream.FlushFinalBlock();


            return Convert.ToBase64String(MStream.ToArray());
        }

 

 

但是下面的代码能够成功

public static string Decrypt(string toDecrypt)
        {
            byte[] keyArray = UTF8Encoding.UTF8.GetBytes("12345678901234567890123456789012");
            byte[] toEncryptArray = Convert.FromBase64String(toDecrypt);
            RijndaelManaged rDel = new RijndaelManaged();
            rDel.Key = keyArray;
            rDel.Mode = CipherMode.ECB;
            rDel.Padding = PaddingMode.PKCS7;
            ICryptoTransform cTransform = rDel.CreateDecryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return UTF8Encoding.UTF8.GetString(resultArray);
        }

        public static string Encrypt(string toEncrypt)
        {
            byte[] keyArray = UTF8Encoding.UTF8.GetBytes("12345678901234567890123456789012");
            byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
            RijndaelManaged rDel = new RijndaelManaged();
            rDel.Key = keyArray; rDel.Mode = CipherMode.ECB; rDel.Padding = PaddingMode.PKCS7;
            ICryptoTransform cTransform = rDel.CreateEncryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }

 

请问可以不用下面的代码 修改第一段代码完成AES加密的任务吗?

还有我想知道问题出在哪里

我做过的尝试:

不是内存流不够大MemoryStream我试过给予很大的容量,尝试设置AesCryptoServiceProvider的padding和mode均无效。

如果第一段的代码的AesCryptoServiceProvider该做DESCryptoServiceProvider 那么代码也能运行成功。

请问问题出在哪里?

 

 

首先,需要引入System.Security.Cryptography命名空间。 以下是C#窗体实现AES加密解密的示例代码: ``` using System; using System.IO; using System.Security.Cryptography; using System.Text; using System.Windows.Forms; namespace AesDemo { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnEncrypt_Click(object sender, EventArgs e) { try { // 获取密钥和向量 string key = txtKey.Text.Trim(); string iv = txtIV.Text.Trim(); byte[] keyBytes = Encoding.UTF8.GetBytes(key); byte[] ivBytes = Encoding.UTF8.GetBytes(iv); // 获取明文 string plaintext = txtPlaintext.Text.Trim(); byte[] plaintextBytes = Encoding.UTF8.GetBytes(plaintext); // 创建AES加密器 using (Aes aes = Aes.Create()) { aes.Key = keyBytes; aes.IV = ivBytes; // 创建加密流 using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, aes.CreateEncryptor(), CryptoStreamMode.Write)) { // 将明文写入加密流 csEncrypt.Write(plaintextBytes, 0, plaintextBytes.Length); csEncrypt.FlushFinalBlock(); // 获取加密结果 byte[] ciphertextBytes = msEncrypt.ToArray(); string ciphertext = Convert.ToBase64String(ciphertextBytes); // 显示加密结果 txtCiphertext.Text = ciphertext; } } } } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void btnDecrypt_Click(object sender, EventArgs e) { try { // 获取密钥和向量 string key = txtKey.Text.Trim(); string iv = txtIV.Text.Trim(); byte[] keyBytes = Encoding.UTF8.GetBytes(key); byte[] ivBytes = Encoding.UTF8.GetBytes(iv); // 获取密文 string ciphertext = txtCiphertext.Text.Trim(); byte[] ciphertextBytes = Convert.FromBase64String(ciphertext); // 创建AES解密器 using (Aes aes = Aes.Create()) { aes.Key = keyBytes; aes.IV = ivBytes; // 创建解密流 using (MemoryStream msDecrypt = new MemoryStream(ciphertextBytes)) { using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, aes.CreateDecryptor(), CryptoStreamMode.Read)) { // 读取解密结果 byte[] plaintextBytes = new byte[ciphertextBytes.Length]; int bytesRead = csDecrypt.Read(plaintextBytes, 0, plaintextBytes.Length); // 显示解密结果 string plaintext = Encoding.UTF8.GetString(plaintextBytes, 0, bytesRead); txtPlaintext.Text = plaintext; } } } } catch (Exception ex) { MessageBox.Show(ex.Message); } } } } ``` 在窗体上添加三个TextBox控件和两个Button控件,分别命名为txtKey、txtIV、txtPlaintext、txtCiphertext、btnEncrypt和btnDecrypt。用户输入密钥、向量和明文,点击“加密”按钮进行加密,点击“解密”按钮进行解密加密解密过程,采用AES算法进行加密解密,使用Base64编码将密文转换为字符串。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值