Can anyone tell me what exactly does this Java code do?
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
byte[] bytes = new byte[20];
synchronized (random)
{
random.nextBytes(bytes);
}
return Base64.encode(bytes);
Step by step explanation will be useful so that I can recreate this code in VB. Thanks
Using code snippets you can get to something like this
Dim randomNumGen As RandomNumberGenerator = RNGCryptoServiceProvider.Create()
Dim randomBytes(20) As Byte
randomNumGen.GetBytes(randomBytes)
return Convert.ToBase64String(randomBytes)
This creates a random number generator (SecureRandom). It then creates a byte array (byte[] bytes), length 20 bytes, and populates it with random data.
This is then encoded using BASE64 and returned.
So, in a nutshell,
- Generate 20 random bytes
- Encode using Base 64
It creates a SHA1 based random number generator (RNG), then Base64 encodes the next 20 bytes returned by the RNG.
I can't tell you why it does this however without some more context :-).
This code gets a cryptographically strong random number that is 20 bytes in length, then Base64 encodes it. There's a lot of Java library code here, so your guess is as good as mine as to how to do it in VB.
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
byte[] bytes = new byte[20];
synchronized (random) { random.nextBytes(bytes); }
return Base64.encode(bytes);
The first line creates an instance of the SecureRandom class. This class provides a cryptographically strong pseudo-random number generator.
The second line declares a byte array of length 20.
The third line reads the next 20 random bytes into the array created in line 2. It synchronizes on the SecureRandom object so that there are no conflicts from other threads that may be using the object. It's not apparent from this code why you need to do this.
The fourth line Base64 encodes the resulting byte array. This is probably for transmission, storage, or display in a known format.
Basically the code above:
- Creates a secure random number generator (for VB see link below)
- Fills a bytearray of length 20 with random bytes
- Base64 encodes the result (you can probably use Convert.ToBase64String(...))
You should find some help here:
http://msdn.microsoft.com/en-us/library/system.security.cryptography.rngcryptoserviceprovider.aspx