paralleldrive / cuid2

Next generation guids. Secure, collision-resistant ids optimized for horizontal scaling and performance.
MIT License
2.6k stars 53 forks source link

Use randomCUID2 with a length > 50, make an index out of bound error #70

Closed Lutty76 closed 8 months ago

Lutty76 commented 8 months ago

Hi,

CUID.randomCUID2(51) make this error

 Caused by: java.lang.StringIndexOutOfBoundsException: begin 1, end 51, length 50
    at java.base/java.lang.String.checkBoundsBeginEnd(String.java:4606)
    at java.base/java.lang.String.substring(String.java:2709)
    at io.github.thibaultmeyer.cuid.CUID.randomCUID2(CUID.java:74)

Probably caused by String hash = CUID.CUIDv2.computeHash(time + CUID.CUIDv2.createEntropy(length) + CUID.CUIDv2.nextCounterValue() + CUID.Common.MACHINE_FINGERPRINT, length); in

    public static CUID randomCUID2(int length) {
        if (length <= 0) {
            throw new CUIDGenerationException("the length must be at least 1");
        } else {
            String time = Long.toString(System.currentTimeMillis(), 36);
            char firstLetter = CUID.CUIDv2.ALPHABET_ARRAY[Math.abs(CUID.Common.nextIntValue()) % CUID.CUIDv2.ALPHABET_ARRAY.length];
            String hash = CUID.CUIDv2.computeHash(time + CUID.CUIDv2.createEntropy(length) + CUID.CUIDv2.nextCounterValue() + CUID.Common.MACHINE_FINGERPRINT, length);
            return new CUID("" + firstLetter + hash.substring(1, length));
        }
    }

That call return (new BigInteger(MessageDigest.getInstance("SHA3-256").digest((content + salt).getBytes(StandardCharsets.UTF_8)))).toString(36);

in

private static String computeHash(String content, int saltLength) {
            String salt = createEntropy(saltLength);

            try {
                return (new BigInteger(MessageDigest.getInstance("SHA3-256").digest((content + salt).getBytes(StandardCharsets.UTF_8)))).toString(36);
            } catch (NoSuchAlgorithmException var4) {
                throw new CUIDGenerationException(var4);
            }
        }

The use of "SHA3-256" algorithm will generate a fixed length output (32 Bytes) your conversion to as string generate a 50 characters length. So when a user demands more of 50 length CUID2, that crash.

ericelliott commented 8 months ago

This is not the repository to report bugs in the Java port you're using.