javarandomgeneratorseediota

Random seed generator


EDIT: Sorry for wrong posting, I'll check the forum locations better next time. I selected an answer as accepted, I think this considers the question closed. Thanks for the helpful replies and tips!

Original: I need to upgrade to the new Iota wallet today. It doesn't have a random seed generator, so I built my own and ran it from NetBeans. Can you give me your opinion? It has to be 81 characters long, and contain A through Z and the number 9. Nothing else. Here's the entire code.

Does this leave anything insecure? Could the code have been cleaner from a standpoint of convention?

    class SeedGenerator    {
    /*
    This is a program to randomize a seed for Iota wallet
    */

    public static void main(String[] args)  {
        System.out.println("*****");
        int seedLength = 81;
        String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ9"; //Only characters allowed in Iota seed are A-Z and number 9
        char[] charArray = alphabet.toCharArray();  //Turn string into array of characters to be referenced by index
        String[] seed = new String[seedLength];
        System.out.print("Random wallet seed is: ");

        for (int i = 0; i < seedLength; i++)    {
            Random newRandomNumber = new Random();
            int seedIndex = newRandomNumber.nextInt(alphabet.length()); //This is an array of index numbers to pull from charArray
//            System.out.print(seedIndex + " "); //Used for testing the random character index range
            seed[i] += charArray[seedIndex];
            System.out.print(charArray[seedIndex] + "");

        }

        System.out.println();
        System.out.println("*****");
    }
}

Solution

  • When asking for code to be reviewed, you should post it here. But regardless of that, there are much more efficient ways to generate a random character.

    One such way would be to generate a random character between 65 and 90, the decimal values for A-Z on the ASCII table. And then, just cast the value as a char to get the actual letter corresponding to the number. However, you say that you want the number 9 to also be included, so you can extend this to 91, and if you get 91, which on the ASCII table is [, add the number 9 to your string instead of that.

    This code accomplishes that quite easily:

    String mySeed = "";
          for(int i=0; i<81; i++)
          {
             int randomNum = (int)(Math.random()*27) + 65;
             if(randomNum==91)
                mySeed+="9";
             else
                mySeed+=(char)randomNum;
          }
          System.out.println(mySeed);
    

    And, as mentioned by @O.O. you can look at generating a secure random number here.