From b9d4901b67010e73a240c24a67f08a0ca5305280 Mon Sep 17 00:00:00 2001 From: ZhouXY108 Date: Tue, 16 Apr 2024 21:04:08 +0800 Subject: [PATCH] =?UTF-8?q?=E9=87=8D=E6=9E=84=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../plusone/commons/util/RandomTools.java | 21 ++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/src/main/java/xyz/zhouxy/plusone/commons/util/RandomTools.java b/src/main/java/xyz/zhouxy/plusone/commons/util/RandomTools.java index 0a977a5..ad2a745 100644 --- a/src/main/java/xyz/zhouxy/plusone/commons/util/RandomTools.java +++ b/src/main/java/xyz/zhouxy/plusone/commons/util/RandomTools.java @@ -1,14 +1,29 @@ package xyz.zhouxy.plusone.commons.util; -import java.security.SecureRandom; +import java.util.Random; +import java.util.concurrent.ThreadLocalRandom; public final class RandomTools { + private RandomTools() { throw new IllegalStateException("Utility class"); } - public static String secureRandomStr(char[] sourceCharacters, int length) { - SecureRandom random = new SecureRandom(); + public static String randomStr(char[] sourceCharacters, int length) { + return randomStr(ThreadLocalRandom.current(), sourceCharacters, length); + } + + /** + * 使用传入的随机数生成器,生成指定长度的字符串 + * + * @param random 随机数生成器。根据需要可以传入 + * {@link java.util.concurrent.ThreadLocalRandom}、{@link java.security.SecureRandom} + * 等,不为空 + * @param sourceCharacters 字符池。字符串的字符将在数组中选,不为空 + * @param length 字符串长度 + * @return 随机字符串 + */ + public static String randomStr(Random random, char[] sourceCharacters, int length) { char[] result = new char[length]; for (int i = 0; i < length; i++) { result[i] = sourceCharacters[random.nextInt(sourceCharacters.length)];