How to generate a secure random alphanumeric string in Java efficiently?

后端 未结 9 1495
半阙折子戏
半阙折子戏 2021-01-01 12:24

How do you generate a secure random (or pseudo-random) alphanumeric string in Java efficiently?

9条回答
  •  醉话见心
    2021-01-01 12:48

    Here's a slightly modified version of my code from the duplicate question.

    public final class RandomString
    {
    
      /* Assign a string that contains the set of characters you allow. */
      private static final String symbols = "ABCDEFGJKLMNPRSTUVWXYZ0123456789"; 
    
      private final Random random = new SecureRandom();
    
      private final char[] buf;
    
      public RandomString(int length)
      {
        if (length < 1)
          throw new IllegalArgumentException("length < 1: " + length);
        buf = new char[length];
      }
    
      public String nextString()
      {
        for (int idx = 0; idx < buf.length; ++idx) 
          buf[idx] = symbols.charAt(random.nextInt(symbols.length()));
        return new String(buf);
      }
    
    }
    

提交回复
热议问题