Search code examples
c#encryption.net-4.0randomrngcryptoserviceprovider

RNGCryptoServiceProvider and Zeros?


walking through some cryptogtaphy stuff , I saw that RNGCryptoServiceProvider has 2 methods :

link

RNGCryptoServiceProvider.GetNonZeroBytes

and

RNGCryptoServiceProvider.GetBytes 

And so I ask :

What is odd with Filling an array of bytes with a cryptographically strong sequence of random value which some (0 or more) of them are zeros ? (it is random values and apparently there wont be many zeros , and still zero is also a regular number)

why did they created the distinguishing ?


Solution

  • Within the .NET framework, GetNonZeroBytes(byte[]) is used when generating PKCS#1 padding for RSA encryption, which uses 0x00 as a seperator.

    Using a tool like Reflector, you can see it used in RSAPKCS1KeyExchangeFormatter.CreateKeyExchange(byte[]) to implement padding as per RFC 2313, section 8.1.2 (RFC 3218 has some nice ASCII art that demonstrates the byte layout more clearly).

    GetNonZeroBytes(byte[]) could also be used to generate salt. The Cryptography StackExchange site has a similar question which suggests that avoiding 0x00 is to help with libraries and APIs that may treat the salt as a zero-terminated string, which would accidentally truncate the salt. However, unless one is using P/Invoke, this is unlikely to be a concern in .NET.