解密AES时出错。输入数据不完整。 vb.net

时间:2018-07-16 12:15:52

标签: vb.net aes

美好的一天。 我正在使用AES加密文本,然后将加密的字节保存到txt文件中。

-

btnencrypt的代码,位于form1.frm

public class ViewModel
{

    public string Input {get; set;}
    public string Output {get; set;}
    public ICommand command {get; set;}
    public Model model {get; set;}

    public ViewModel() 
    {
      model = new Model();
    }

    // When the button is pressed, model.input = Input and then execute model.FancyMethod()

}

-

btnDecrypt的代码在form2.frm中

Dim aes_CryptoTransform As ICryptoTransform = AesCryptoServiceProvider.Create.CreateEncryptor(aesKeySet.Key, aesKeySet.IV)
Dim textBytes() As Byte = System.Text.Encoding.ASCII.GetBytes(rtb_plaintext.Text)

Dim encrypted() As Byte
using msEncrypt As New MemoryStream()
     using csEncrypt As New CryptoStream(textBytes, aes_CryptoTransform, CryptoStreamMode.write)
          using textStream as New StreamWriter(csEncrypt) 
               swEncrypt.Write(plainText)
          End Using
          encrypted = msEncrypt.ToArray()
          csEncrypt.close()
     End Using
End Using

dim textDirectoryPath as String = "C:\encryptText.text"
using textFilestream as new Filestream(textDirectoryPath, filemode.create)
     textFilestream.write(encrypted, 0, encrypted.length)
     textFilestream.close()
end using

- 如果我单击解密按钮,则会收到一条错误消息,提示“输入数据不是完整的块” 看来我做错了什么?

1 个答案:

答案 0 :(得分:-1)

我认为您忘记了致电swEncrypt.FlushFinalBlock()。我没有太多的VB经验,但是错误意味着加密的数据没有填充到完整的块大小。我的C#代码与您的C#代码相似,除了我先写字节然后调用FlushFinalBlock()

请参见C#中的示例:

private IEncryptionResponse Encrypt(byte[] data, IKey key)
{
    try
    { 
        using (var symmetricAlgorithm = new AesCryptoServiceProvider())
        {
            symmetricAlgorithm.GenerateIV();
            byte[] iv = symmetricAlgorithm.IV;

            using (var msEncrypt = new MemoryStream())
            {
                using (var encryptor = symmetricAlgorithm.CreateEncryptor(key.RawKey, iv))
                {
                    using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        try
                        {
                            csEncrypt.Write(data, 0, data.Length);
                            csEncrypt.FlushFinalBlock();
                            var encryptedBytes = msEncrypt.ToArray();

                            return Convert.ToBase64String(iv.Add(encryptedBytes));
                        }
                        finally
                        {
                           symmetricAlgorithm.Clear();
                        }
                    }
                }
            }
        }
    }
    catch (Exception e)
    {
        throw new EncryptionException("Encryption error", e);
    }

}