Generate random bytes with cryptography feature in WinRT(UWP)

To generate random bytes in WinRT, we need to use the APIs provided in Windows.Security.Cryptography.CryptographicBuffer

Use the following codes to generate a random buffer:

1
Windows.Security.Cryptography.CryptographicBuffer.GenerateRandom(length);

And use the IBuffer.ToArray() to convert the random buffer into byte array.
Like this:

1
Windows.Security.Cryptography.CryptographicBuffer.GenerateRandom(length).ToArray();

The equivalent legacy .NET codes can be written like this:

1
2
RandomNumberGenerator random = new RNGCryptoServiceProvider();
random.GetBytes(byteArray);