开发者

OutOfMemoryException at RNGCryptoServiceProvider.GetBytes(). How can I create huge randomly generated file?

I want to create a file with a cryptographically strong sequence of random values. This is the code

int bufferLength = 719585280;
byte[] random = new byte[bufferLength];
RNGCryptoServiceProvider rng = new RNGCryptoServi开发者_JAVA技巧ceProvider();
rng.GetBytes(random);
File.WriteAllBytes("crypto.bin",random);

The problem is it returns OutOfMemoryException at rng.GetBytes(random);. I need a file with that kind of size(no more, no less). How can I solve this? Thanks.


Simply do it in chunks:

byte[] buffer = new byte[16 * 1024];
int bytesToWrite = 719585280;
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

using (Stream output = File.Create("crypto.bin"))
{
    while (bytesToWrite > 0)
    {
        rng.GetBytes(buffer);
        int bytesThisTime = Math.Min(bytesToWrite, buffer.Length);
        output.Write(buffer, 0, bytesThisTime);
        bytesToWrite -= bytesThisTime;
    }
}

There's no reason to generate the whole thing in memory in one go, basically.


int fileSize = 719585280;
var bufLength = 4096;
byte[] random = new byte[bufLength];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

var bytesRemaining = fileSize;

using(var fs=File.Create("c:\crypto.bin"))
{
    while(bytesRemaining > 0)
    {
        rng.GetBytes(random);
        var bytesToWrite = Math.Min(bufLength, bytesRemaining);
        fs.Write(random, 0, bytesToWrite);
        bytesRemaining -= bytesToWrite;
    }
}


Try generating it in parts and stream it together into the file.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜