2

There is something about SecureRandom that i don't quiet understand. Take for example this code here:

import java.security.SecureRandom;
import java.math.BigInteger;

public final class SessionIdentifierGenerator{
private static SecureRandom random = new SecureRandom();

    public static void main(String[] args) {
           nextSessionId(); 
    }

  public static String nextSessionId(){
         BigInteger ss =  new BigInteger(130, random);
         System.out.println(ss);
         System.out.println(ss.toString(32));
         return null;
  }

}

one Example of the out put it will be:

1107894191825737787218556533052298445977

q1fikf1m0jagvlrmbtdah0mh4p

Since BigInteger is integers the output is quiet predictable, but the thing i don't understand is where is that random string coming from since i apply toString() method, so i was expentiong that this string it will be the same number sequence but as a string, so how and why is this happing?

thanks. ps: i don't if it has been ask before, but i didn't find anything... original code wiki

Community
  • 1
  • 1
Jorge Y. C. Rodriguez
  • 3,394
  • 5
  • 38
  • 61

3 Answers3

5

You're calling toString(32) which, as its javadoc indicates,

Returns the String representation of this BigInteger in the given radix.

So you're asking the string representation of the number in base 32 instead of the traditional base 10. If you passed 16, you would get the number in hexadecimal format, with digits going from 0 to f. If you passed 8, you would get it as an octal number, with digits going from 0 to 7.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
1

Your .toString(32) is not making it 32 chars wide. It's showing it as a base 32 number.

Corey Ogburn
  • 24,072
  • 31
  • 113
  • 188
1

It's because you are calling toString with a radix

This converts the integer to a String, using a radix. Hexadecimal (0123456789abcdef) for example is radix 16. You are using radix 32 so you get a lot more different characters. It's converting the entire number to number base 32 before outputting as a String.

If you simply want the number as a string representation, calling the normal .toString method is enough. This is actually done by the System.out.println method when you call

System.out.println(ss);

Compare that output with

System.out.println(ss.toString());

And you will see that it is always the same.

Simon Forsberg
  • 13,086
  • 10
  • 64
  • 108