java - 如何在参数中使用字符串创建固定长度的 BigInteger

标签 java hash sha1 biginteger

我使用以下代码生成一个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/

相关文章:

java - Javauto编译失败(入门)

PHP:生成唯一用户 key 的选项

python - 在 Python 中生成多个文件的一个 MD5/SHA1 校验和

git - 在提交中获取变更集(或差异)的 git SHA1 哈希

java - 多个 maven pom.xml 文件

java - 线程中的异常 "main"java.lang.StringIndexOutOfBoundsException : String index out of range

java - 号码跑者计划

php - 确定以前在实现随机盐时是否使用过密码

python - 在Python中使用唯一键对字符串进行哈希处理的安全性

encryption - SSL 加密、SHA-1 和 SHA-2