2014-09-26 29 views
0

我使用以下代碼生成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); 
} 

在另一個方面,我有用下面的代碼生成的許多編號(的BigInteger值):

int idLength = 160; 
Random r = new java.util.Random(); 
BigInteger id = new BigInteger(idLength, r); 

所以我有一個id分鐘和ID max和我想有所有散列由第一個代碼生成的值在min和max內由第二個代碼生成。 我怎麼能得到哈希函數的結果$ maxBitLength = idLength $(類似於$ new BigInteger(String str,int numBits)$)

+1

請記住'str.getBytes()'返回*默認平臺編碼*中的字節,這些字節可能因系統的不同而出現意外和不合意的情況。通常最好使用'str.getBytes(java.nio.charset.StandardCharsets.UTF_8)'或者在舊版本的Java中''str.getBytes(「UTF-8」)'(或者任何字符設置你正在使用)。 – 2014-09-26 17:32:12

+0

感謝@DavidConrad提供'str.getBytes()'。 – bass 2014-09-26 17:50:00

回答

1

如果你有一個最小值和一個最大值,重新期待,那麼你應該只是計算min.add(hash(str).mod(max.subtract(min)))

+0

謝謝!我可以得到最小值和最大值,但它會在我的應用程序中產生糟糕的性能。 (我有很多ID) – bass 2014-09-26 17:01:05

相關問題