The .NET Framework has the RandomNumberGenerator
class for generating cryptographically-secure random bytes. One of its main methods, GetBytes
, has the signature void GetBytes (byte[] data)
- it takes a byte array as a parameter and fills it with random bytes, rather than returning a byte array. Why is this? Are there security reasons for operating on an existing array instead of creating a new one?
I don't think security could be really the reason for the byte[]
parameter in a managed framework. I don't see any difference with it being generated by the method and outside of it, as a byte[]
- an array of a base type - is not likely to have multiple implementations. If there would be difference possible then it would make more sense to have the method generate the byte array.
Without it, the efficiency reason already given makes more sense; the byte array may be larg(-ish) after all, and you cannot duplicate the efficiency of the call that takes the bytes. There is also another method that additionally takes an offset and "count" of bytes to an existing array. This lets you directly generate bytes to an array that can also hold other data (e.g. a concatenation of IV and ciphertext in a byte array). Of course the single parameter is just a special case / convenience method for that call. The multi-parameter one is the most important one for efficiency as you would otherwise have to duplicate the ciphertext as well; arrays cannot be shrunk after all. It would be strange to create a method with the same name but with a very different method signature.
Other frameworks such as the Java JCA have the same methods for SecureRandom
. So it is likely that the authors knew about such frameworks and decided to mimic these existing API's, unless there was sufficient reason for change.