索引超出了数组的界限.Rijndael加密



在花时间阅读本文之前,请参阅下面的自我回答。问题是输入无效。


当我试图解密一些字符串时,它会抛出以下异常:

    "   at System.Security.Cryptography.RijndaelManagedTransform.DecryptData(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount, Byte[]& outputBuffer, Int32 outputOffset, PaddingMode paddingMode, Boolean fLast)
       at System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount)
       at System.Security.Cryptography.CryptoStream.FlushFinalBlock()
       at System.Security.Cryptography.CryptoStream.Dispose(Boolean disposing)
       at System.IO.Stream.Close()
       at System.IO.Stream.Dispose()
       at EBookReader.cryptography.DecryptString(String message, String KeyString, String IVString) in C:\Users\XWare\Documents\Visual Studio 2008\Projects\EBookReader\EBookReader\cryptography.cs:line 94"

在调试过程中,它在以下行抛出异常:

    byte[] messageBytes = Convert.FromBase64String(message);

我认为这个问题只会在要解密的字符串太大时出现,因为当我试图加密和解密短字符串时,比如"嗨,我是X-Ware",它可以很好地进行

    public static string DecryptString(string message, string KeyString, string IVString)
    {
        byte[] Key = ASCIIEncoding.UTF8.GetBytes(KeyString);
        byte[] IV = ASCIIEncoding.UTF8.GetBytes(IVString);
        string decrypted = null;
        RijndaelManaged rj = new RijndaelManaged();
        rj.BlockSize = 256;
        rj.Key = Key;
        rj.IV = IV;
        rj.Mode = CipherMode.CBC;
        rj.Padding = PaddingMode.PKCS7;
        try
        {
            MemoryStream ms = new MemoryStream();
            Encoding enc = new ASCIIEncoding();
            using (CryptoStream cs = new CryptoStream(ms, rj.CreateDecryptor(Key, IV), CryptoStreamMode.Write))
            {
                byte[] messageBytes = Convert.FromBase64String(message);
                cs.Write(messageBytes, 0, messageBytes.Length);
                cs.FlushFinalBlock();  
            }// This is line 94
            byte[] encoded = ms.ToArray();
            decrypted = enc.GetString(encoded);
            ms.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine("An error occurred: {0}", e.Message);
        }
        finally
        {
            rj.Clear();
        }
        return decrypted;
    }

有什么建议吗?!

附言:我写了一条评论给你看第94行//这是第94行

FlushFinalBlock方法仅用于刷新最后一个完整或部分字节块。因此,如果您编写的块大小超过一个,则不适合进行方法调用。在尝试从内存流中读取之前,请尝试简单地关闭加密流。

要在代码上下文中执行此操作,只需删除行cs.FlushFinalBlock()。。。

问题是我作为Base64字符串传递的字符串无效问题只是在输入文件中,这使得无法解密

Thanx所有

相关内容

  • 没有找到相关文章

最新更新