为什么Rijndael加密代码不适用于大文件?

时间:2011-10-01 10:15:15

标签: .net vb.net rijndael

我使用以下Rijndael代码多次进行加密。但为什么它不能加密4.2 GB的ISO文件?实际上我的电脑有16GB内存,不应该是内存问题。我使用Windows 7旗舰版。使用Visual Studio 2010(VB.NET项目)将代码编译为winform(.Net 4)。

我已经检查过ISO文件是否正常,可以作为虚拟驱动器安装,甚至可以刻录到DVD ROM。所以这不是ISO文件问题。

我的问题:为什么以下代码无法加密大小为4.2GB的ISO文件?这是由Windows / .NET 4实现的限制引起的吗?

Private Sub DecryptData(inName As String, outName As String, rijnKey() As Byte, rijnIV() As Byte)

    'Create the file streams to handle the input and output files.
    Dim fin As New IO.FileStream(inName, System.IO.FileMode.Open, System.IO.FileAccess.Read)
    Dim fout As New IO.FileStream(outName, System.IO.FileMode.OpenOrCreate,
       System.IO.FileAccess.Write)
    fout.SetLength(0)

    'Create variables to help with read and write.
    Dim bin(100) As Byte 'This is intermediate storage for the encryption.
    Dim rdlen As Long = 0 'This is the total number of bytes written.
    Dim totlen As Long = fin.Length 'Total length of the input file.
    Dim len As Integer 'This is the number of bytes to be written at a time.

    'Creates the default implementation, which is RijndaelManaged.
    Dim rijn As New Security.Cryptography.RijndaelManaged
    Dim encStream As New Security.Cryptography.CryptoStream(fout,
       rijn.CreateDecryptor(rijnKey, rijnIV), Security.Cryptography.CryptoStreamMode.Write)

    'Read from the input file, then encrypt and write to the output file.
    While rdlen < totlen
        len = fin.Read(bin, 0, 100)
        encStream.Write(bin, 0, len)
        rdlen = Convert.ToInt32(rdlen + len)
    End While

    encStream.Close()
    fout.Close()
    fin.Close()
End Sub

2 个答案:

答案 0 :(得分:9)

rdlen = Convert.ToInt32(rdlen + len)

Int32可以表示有符号整数,其值范围从负2,147,483,648到正2,147,483,647,因为4.2GB大约是我的两倍,我猜rdlen永远不会超过totlen因此你让自己永无止境。

如果VB.NET像C#一样工作(我怀疑它确实如此),你只需删除转换

rdlen = rdlen + len

Long + Int的结果将是Long。其中Long是64位有符号整数,Int是32位有符号整数。

答案 1 :(得分:2)

尝试改变:

rdlen = Convert.ToInt32(rdlen + len)

到此:

rdlen = Convert.ToInt64(rdlen + len)