From da1149312a3ecce82a35dbc0a2726466a919982e Mon Sep 17 00:00:00 2001 From: Julian Chennales Date: Wed, 1 Jun 2022 15:37:36 -0300 Subject: [PATCH] Add configurable hash mod base Also increase JUnit 4 version to avoid CVE flagging --- pom.xml | 2 +- src/main/java/org/hashids/Hashids.java | 15 +++++++++++++-- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/pom.xml b/pom.xml index 2e16731..5cd3374 100644 --- a/pom.xml +++ b/pom.xml @@ -198,7 +198,7 @@ junit junit - 4.13.1 + 4.13.2 test diff --git a/src/main/java/org/hashids/Hashids.java b/src/main/java/org/hashids/Hashids.java index 6d688ea..f1354b8 100644 --- a/src/main/java/org/hashids/Hashids.java +++ b/src/main/java/org/hashids/Hashids.java @@ -31,12 +31,14 @@ public class Hashids { private static final int MIN_ALPHABET_LENGTH = 16; private static final double SEP_DIV = 3.5; private static final int GUARD_DIV = 12; + private static final int DEFAULT_HASH_MOD_BASE = 100; private final String salt; private final int minHashLength; private final String alphabet; private final String seps; private final String guards; + private final int hashModBase; public Hashids() { this(DEFAULT_SALT); @@ -47,12 +49,21 @@ public Hashids(String salt) { } public Hashids(String salt, int minHashLength) { - this(salt, minHashLength, DEFAULT_ALPHABET); + this(salt, minHashLength, DEFAULT_ALPHABET, DEFAULT_HASH_MOD_BASE); } + public Hashids(String salt, int minHashLength, int hashModBase) { + this(salt, minHashLength, DEFAULT_ALPHABET, hashModBase); + } + public Hashids(String salt, int minHashLength, String alphabet) { + this(salt, minHashLength, alphabet, DEFAULT_HASH_MOD_BASE); + } + + public Hashids(String salt, int minHashLength, String alphabet, int hashModBase) { this.salt = salt != null ? salt : DEFAULT_SALT; this.minHashLength = minHashLength > 0 ? minHashLength : DEFAULT_MIN_HASH_LENGTH; + this.hashModBase = hashModBase != 0? hashModBase : DEFAULT_HASH_MOD_BASE; final StringBuilder uniqueAlphabet = new StringBuilder(); for (int i = 0; i < alphabet.length(); i++) { @@ -226,7 +237,7 @@ public static int checkedCast(long value) { private String _encode(long... numbers) { long numberHashInt = 0; for (int i = 0; i < numbers.length; i++) { - numberHashInt += (numbers[i] % (i + 100)); + numberHashInt += (numbers[i] % (i + hashModBase)); } String alphabet = this.alphabet; final char ret = alphabet.charAt((int) (numberHashInt % alphabet.length()));