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

后端 未结 9 1499
半阙折子戏
半阙折子戏 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:51

        String chrs = "0123456789abcdefghijklmnopqrstuvwxyz-_ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        SecureRandom secureRandom = SecureRandom.getInstanceStrong();
        // 9 is the length of the string you want
        String customTag = secureRandom.ints(9, 0, chrs.length()).mapToObj(i -> chrs.charAt(i))
          .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append).toString();
        System.out.println(customTag);
    

    Examples:

    // q3HX6EctP
    // WjRrMjQT4
    // sX-Piq4DB
    

提交回复
热议问题