【问题标题】:Unable to create CryptoStream to read from - System.NotSupportedException无法创建要从中读取的 CryptoStream - System.NotSupportedException
【发布时间】:2012-08-24 08:26:31
【问题描述】:

解密文件的代码真的很简单(三重des加密):

        FileStream fin = new FileStream(FilePath, FileMode.Open, FileAccess.Read);
        TripleDES tdes = new TripleDESCryptoServiceProvider();
        CryptoStream cs = new CryptoStream(fin, tdes.CreateDecryptor(key, iv),CryptoStreamMode.Read); //<---- Exceptions

而且它不起作用。 'cs' 无效,无法从中读取。创建 CryptoStream 时有一些例外情况:

Length = 'cs.Length' threw an exception of type 'System.NotSupportedException'
base {System.SystemException} = {"Stream does not support seeking."}

为什么我无法创建加密流并从中读取以及如何解决此问题?

[添加]

感谢您的回复,现在对我来说更清楚了。但是 - 仍然无法从“cs”中读取。

加密:

FileStream fout = new FileStream(FilePath, FileMode.OpenOrCreate, FileAccess.Write);
TripleDES tdes = new TripleDESCryptoServiceProvider();
CryptoStream cs = new CryptoStream(fout, tdes.CreateEncryptor(key, iv), CryptoStreamMode.Write);

byte[] d = Encoding.ASCII.GetBytes(Data);
cs.Write(d, 0, d.Length);
cs.WriteByte(0);

cs.Close();
fout.Close();

在其他地方定义了 iv 和 key。并且,解密 - 整个方法:

    FileStream fin = new FileStream(FilePath, FileMode.Open, FileAccess.Read);
    TripleDES tdes = new TripleDESCryptoServiceProvider();
    CryptoStream cs = new CryptoStream(fin, tdes.CreateDecryptor(key, iv),CryptoStreamMode.Read);

    StringBuilder SB = new StringBuilder();
    int ch;
    for (int i = 0; i < fin.Length; i++)
    {
     ch = cs.ReadByte(); //Exception - CryptographicException: Bad data
     if (ch == 0)
     break;
     SB.Append(Convert.ToChar(ch));
    }
  cs.Close();
  fin.Close();

如您所见,与加密代码中的密钥和 iv 相同。但是仍然无法从“cs”流中读取 - 抛出异常。你怎么看 - 这里有什么问题?

这是我的钥匙,我用过:

public static byte[] key = { 21, 10, 64, 10, 100, 40, 200, 4,
                    21, 54, 65, 246, 5, 62, 1, 54,
                    54, 6, 8, 9, 65, 4, 65, 9};

    private static byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0 };

【问题讨论】:

    标签: c# tripledes notsupportedexception cryptostream


    【解决方案1】:

    在我看来,您正在观看 Visual Studios 工具中的 sc.Length 属性,该工具专用于检查变量,并且您在那里遇到异常。如果是这样,请忽略它们,如果您在代码中使用 Length,它们将是相关的。流不支持需要了解内部所有数据的功能是很正常的。

    编辑

    首先,您假设加密文件的长度等于解密数据的长度。我想这可能是真的,但我对此表示怀疑。

    尝试:

    var textReader = new StreamReader(cs);// you might need to specify encoding 
    var text = textReader.ReadToEnd();
    

    请注意,这会将整个文件读入内存,这对于大文件来说是个问题。

    如果我要编写此代码,我将使用StreamWritter 写入CryptoStreamStreamReader 以从中读取代码。

    【讨论】:

      【解决方案2】:

      您的代码在我的机器上没有错误(VS2010、.NET 4、Windows)。您在哪个客户端配置文件/平台上运行它?该错误表明您的 FileStream 是不支持查找的类型,是正常的 .NET FileStream 吗?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多