From 88f96415f3c3b87285b94d4b86a33c1a2abdebfb Mon Sep 17 00:00:00 2001 From: czarekm Date: Tue, 23 Jul 2024 13:56:08 +0200 Subject: [PATCH] Fix for ArrayIndexOutOfBoundsException when random number is Integer.MIN_VALUE --- src/main/java/io/github/thibaultmeyer/cuid/CUID.java | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/main/java/io/github/thibaultmeyer/cuid/CUID.java b/src/main/java/io/github/thibaultmeyer/cuid/CUID.java index aae7975..a3e0180 100644 --- a/src/main/java/io/github/thibaultmeyer/cuid/CUID.java +++ b/src/main/java/io/github/thibaultmeyer/cuid/CUID.java @@ -66,7 +66,7 @@ public static CUID randomCUID2(final int length) { } final String time = Long.toString(System.currentTimeMillis(), NUMBER_BASE); - final char firstLetter = CUIDv2.ALPHABET_ARRAY[Math.abs(Common.nextIntValue()) % CUIDv2.ALPHABET_ARRAY.length]; + final char firstLetter = CUIDv2.ALPHABET_ARRAY[safeAbs(Common.nextIntValue()) % CUIDv2.ALPHABET_ARRAY.length]; final String hash = CUIDv2.computeHash( time + CUIDv2.createEntropy(length) + CUIDv2.nextCounterValue() + Common.MACHINE_FINGERPRINT, length); @@ -177,6 +177,11 @@ public int hashCode() { return Objects.hash(value); } + // Always return non-negative value (including Integer.MIN_VALUE) + private static int safeAbs(int a) { + return a == Integer.MIN_VALUE ? 0 : Math.abs(a); + } + /** * CUID Version 1. * @@ -252,7 +257,7 @@ private static final class CUIDv2 { */ private static synchronized int nextCounterValue() { - counter = counter < Integer.MAX_VALUE ? counter : Math.abs(Common.nextIntValue()); + counter = counter < Integer.MAX_VALUE ? counter : safeAbs(Common.nextIntValue()); return counter++; } @@ -268,7 +273,7 @@ private static String createEntropy(final int length) { final StringBuilder stringBuilder = new StringBuilder(length); while (stringBuilder.length() < length) { - primeNumber = PRIME_NUMBER_ARRAY[Math.abs(Common.nextIntValue()) % PRIME_NUMBER_ARRAY.length]; + primeNumber = PRIME_NUMBER_ARRAY[safeAbs(Common.nextIntValue()) % PRIME_NUMBER_ARRAY.length]; stringBuilder.append(Integer.toString(primeNumber * Common.nextIntValue(), NUMBER_BASE)); }