我使用以下代码生成一个bigInteger作为字符串的哈希值。
public static BigInteger hash(String str) throws NoSuchAlgorithmException {
MessageDigest digest = MessageDigest.getInstance("SHA1");
digest.reset();
byte[] input = digest.digest(str.getBytes());
return new BigInteger(1,input);
}
另一方面,我有许多使用以下代码生成的 id(BigInteger 值):
int idLength = 160;
Random r = new java.util.Random();
BigInteger id = new BigInteger(idLength, r);
所以我有一个 id min 和一个 id max,并且我希望第一个代码生成的所有哈希值都在第二个代码生成的最小值和最大值内。 我怎样才能得到带有 $maxBitLength = idLength$ 的哈希函数的结果(类似于 $new BigInteger (String str, int numBits)$)
最佳答案
如果您有期望的最小值和最大值,那么您应该只计算 min.add(hash(str).mod(max.subtract(min)))
。
关于java - 如何在参数中使用字符串创建固定长度的 BigInteger,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26064370/