Skip to content

Really the Cuid2 algorithm? #7

Description

@sdavids

Describe the bug

I am unsure if this implementation is the same algorithm as the original.

To Reproduce

The entropy is computed differently:

https://github.com/paralleldrive/cuid2/blob/53e246b0919c8123e492e6b6bbab41fe66f4b462/src/index.js#L7-L14

private static String createEntropy(final int length) {
int primeNumber;
final StringBuilder stringBuilder = new StringBuilder(length);
while (stringBuilder.length() < length) {
primeNumber = PRIME_NUMBER_ARRAY[Math.abs(Common.nextIntValue()) % PRIME_NUMBER_ARRAY.length];
stringBuilder.append(Integer.toString(primeNumber * Common.nextIntValue(), NUMBER_BASE));
}
return stringBuilder.toString();


The hash is computed differently:

https://github.com/paralleldrive/cuid2/blob/53e246b0919c8123e492e6b6bbab41fe66f4b462/src/index.js#L31-L35

private static String computeHash(final String content, final int saltLength) {
final String salt = createEntropy(saltLength);
try {
return new BigInteger(MessageDigest.getInstance("SHA3-256").digest((content + salt).getBytes(StandardCharsets.UTF_8)))
.toString(NUMBER_BASE);
} catch (final NoSuchAlgorithmException exception) {
throw new CUIDGenerationException(exception);
}
}


The alphabet is accessed differently:

https://github.com/paralleldrive/cuid2/blob/53e246b0919c8123e492e6b6bbab41fe66f4b462/src/index.js#L37-L39

final char firstLetter = CUIDv2.ALPHABET_ARRAY[Math.abs(Common.nextIntValue()) % CUIDv2.ALPHABET_ARRAY.length];

https://github.com/ai/nanoid?tab=readme-ov-file

random % alphabet is a popular mistake [...] [t]he distribution will not be even; there will be a lower chance for some symbols to appear compared to others.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    help wantedExtra attention is neededquestionFurther information is requested

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions