From 18f329bb1979787366f99a12115c92d23b790ee9 Mon Sep 17 00:00:00 2001 From: buwehh Date: Wed, 2 Apr 2025 15:15:37 +0800 Subject: [PATCH] fix(randomString): replace ThreadLocalRandom with SecureRandom for cryptographic safety - Replaced ThreadLocalRandom.current() with a static SecureRandom instance to address potential security vulnerabilities in random string generation. - Maintained existing behavior for length handling and character selection. - SecureRandom provides cryptographically strong randomness, required for security-sensitive use cases (e.g., tokens, passwords). This fixes a vulnerability where predictable random values could be exploited due to the use of a non-cryptographic RNG. The change aligns with the original implementation's security guarantees. --- .../java/me/zhyd/oauth/utils/RandomUtil.java | 24 ++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/src/main/java/me/zhyd/oauth/utils/RandomUtil.java b/src/main/java/me/zhyd/oauth/utils/RandomUtil.java index e68a2c6a..78c42dc9 100644 --- a/src/main/java/me/zhyd/oauth/utils/RandomUtil.java +++ b/src/main/java/me/zhyd/oauth/utils/RandomUtil.java @@ -1,5 +1,7 @@ package me.zhyd.oauth.utils; +import java.security.SecureRandom; +import java.util.Random; import java.util.concurrent.ThreadLocalRandom; /** @@ -22,6 +24,26 @@ public class RandomUtil { * @param length 字符串的长度 * @return 指定长度的随机字符串 */ + + /* A cryptographically strong random number generator object for use with randomString(). + **/ + private static Random randGen = new SecureRandom(); + + /** + * Array of numbers and letters of mixed case. Numbers appear in the list + * twice so that there is a more equal chance that a number will be picked. + * We can use the array to get a random number or letter by picking a random + * array index. + */ + private static char[] numbersAndLetters = ("0123456789abcdefghijklmnopqrstuvwxyz" + + "ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray(); + + /** + * Returns a random String of numbers and letters (lower and upper case) + * of the specified length. The method uses a cryptographically strong + * random number generator as provided by {@link SecureRandom} + */ + public static String randomString(int length) { final StringBuilder sb = new StringBuilder(length); @@ -30,7 +52,7 @@ public static String randomString(int length) { } int baseLength = BASE_CHAR_NUMBER.length(); for (int i = 0; i < length; i++) { - int number = ThreadLocalRandom.current().nextInt(baseLength); + int number = SERCURE_RANDOM.nextInt(baseLength); sb.append(BASE_CHAR_NUMBER.charAt(number)); } return sb.toString();