簡體   English   中英

如何為android中的字符串輸入生成唯一的hash代碼......?

[英]How to generate a unique hash code for string input in android…?

我想為 android 中的字符串生成一個唯一的 hash 代碼。 是否有任何預定義的庫,或者我們必須手動生成。 請任何知道的人提供鏈接或代碼。

這取決於你的意思:

  • 如前所述, String.hashCode()為您提供 32 位 hash 代碼。

  • 如果你想要(比如說)一個 64 位的哈希碼,你可以自己輕松地實現它。

  • 如果你想要一個字符串的加密 hash,Java 加密庫包括 MD5、SHA-1 等的實現。 您通常需要將字符串轉換為字節數組,然后將其提供給 hash 生成器/摘要生成器。 例如,請參閱@Bryan Kemp 的回答。

  • 如果您想要一個有保證的唯一hash 代碼,那么您就不走運了。 哈希和 hash 代碼是非唯一的。

一個長度為 N 的 Java 字符串有65536 ^ N可能的狀態,並且需要一個具有16 * N位的 integer 來表示所有可能的值。 If you write a hash function that produces integer with a smaller range (eg less than 16 * N bits), you will eventually find cases where more than one String hashes to the same integer; 即 hash 代碼不能是唯一的。 這被稱為鴿巢原理,並且有一個直接的數學證明。 (你不能打數學贏!)

但是,如果可以接受具有非常小的非唯一性的“可能是唯一的”,那么加密哈希是一個很好的答案。 數學將告訴您 hash 必須有多大(即多少位)才能實現給定(足夠低)的非唯一性概率。

這是我用來創建消息摘要哈希的 class

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Sha1Hex {

    public String makeSHA1Hash(String input)
            throws NoSuchAlgorithmException, UnsupportedEncodingException
        {
            MessageDigest md = MessageDigest.getInstance("SHA1");
            md.reset();
            byte[] buffer = input.getBytes("UTF-8");
            md.update(buffer);
            byte[] digest = md.digest();

            String hexStr = "";
            for (int i = 0; i < digest.length; i++) {
                hexStr +=  Integer.toString( ( digest[i] & 0xff ) + 0x100, 16).substring( 1 );
            }
            return hexStr;
        }
}
String input = "some input string";
int hashCode = input.hashCode();
System.out.println("input hash code = " + hashCode);

您可以使用此代碼生成給定字符串的代碼。

int hash = 7;
for (int i = 0; i < strlen; i++) {
    hash = hash*31 + charAt(i);
}

我使用它作為我的EhCacheManager Memory map 的密鑰進行了測試。

我想它更干凈

   /**
     * Return Hash256 of String value
     *
     * @param text
     * @return 
     */
    public static String getHash256(String text) {
        try {
            return org.apache.commons.codec.digest.DigestUtils.sha256Hex(text);
        } catch (Exception ex) {
            Logger.getLogger(HashUtil.class.getName()).log(Level.SEVERE, null, ex);
            return "";
        }
    }

我正在使用 maven 但這是 jar commons-codec-1.9.jar

幾行 java 代碼。

public static void main(String args[]) throws Exception{
       String str="test string";
       MessageDigest messageDigest=MessageDigest.getInstance("MD5");
       messageDigest.update(str.getBytes(),0,str.length());
       System.out.println("MD5: "+new BigInteger(1,messageDigest.digest()).toString(16));
}

讓我們看一下股票的 hashCode() 方法:

public int hashCode() {
    int h = hash;
    if (h == 0 && count > 0) {
        for (int i = 0; i < count; i++) {
            h = 31 * h + charAt(i);
        }
        hash = h;
    }
    return h;
}

上面的代碼塊來自 java.lang.String class。 如您所見,它是一個 32 位 hash 代碼,如果您在小規模數據上使用它就足夠了。 如果您正在尋找超過 32 位的 hash 代碼,您可能想查看此鏈接: http://www.javamex.com/tutorials/collections/strong_hash_code_implementation.shtml

對我來說它有效

   public static long getUniqueLongFromString (String value){
       return  UUID.nameUUIDFromBytes(value.getBytes()).getMostSignificantBits();
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM