【问题标题】:How to create a fixe length BigInteger using a String in argument如何在参数中使用字符串创建固定长度的 BigInteger
【发布时间】:2014-11-21 17:58:15
【问题描述】:

我使用以下代码生成一个 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 最小值和一个 id 最大值,我希望第一个代码生成的所有哈希值都在最小值范围内,而最大值由第二个代码生成。 如何使用 $maxBitLength = idLength$ 获得哈希函数的结果(类似于 $new BigInteger (String str, int numBits)$)

【问题讨论】:

  • 请记住,str.getBytes()默认平台编码 形式返回字节,这可能会因系统而异,并且会以意想不到和不受欢迎的方式发生变化。通常最好使用str.getBytes(java.nio.charset.StandardCharsets.UTF_8) 明确指定字符集,或者在旧版本的Java 上使用str.getBytes("UTF-8")(或您使用的任何字符集)。
  • 感谢@DavidConrad str.getBytes()

标签: java hash sha1 biginteger


【解决方案1】:

如果您有期望的最小值和最大值,那么您应该只计算min.add(hash(str).mod(max.subtract(min)))

【讨论】:

  • 谢谢!我可以获得最小值和最大值,但它会在我的应用程序中产生较差的性能。 (我有很多 id)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-15
  • 2020-01-14
  • 1970-01-01
  • 1970-01-01
  • 2015-06-14
  • 1970-01-01
相关资源
最近更新 更多