简体   繁体   English

如何为android中的字符串输入生成唯一的hash代码......?

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

I wanted to generate a unique hash code for a string in put in android.我想为 android 中的字符串生成一个唯一的 hash 代码。 Is there any predefined library is there or we have to generate manually.是否有任何预定义的库,或者我们必须手动生成。 Please any body if knows please present a link or a code stuff.请任何知道的人提供链接或代码。

It depends on what you mean:这取决于你的意思:

  • As mentioned String.hashCode() gives you a 32 bit hash code.如前所述, String.hashCode()为您提供 32 位 hash 代码。

  • If you want (say) a 64-bit hashcode you can easily implement it yourself.如果你想要(比如说)一个 64 位的哈希码,你可以自己轻松地实现它。

  • If you want a cryptographic hash of a String, the Java crypto libraries include implementations of MD5, SHA-1 and so on.如果你想要一个字符串的加密 hash,Java 加密库包括 MD5、SHA-1 等的实现。 You'll typically need to turn the String into a byte array, and then feed that to the hash generator / digest generator.您通常需要将字符串转换为字节数组,然后将其提供给 hash 生成器/摘要生成器。 For example, see @Bryan Kemp's answer.例如,请参阅@Bryan Kemp 的回答。

  • If you want a guaranteed unique hash code, you are out of luck.如果您想要一个有保证的唯一hash 代码,那么您就不走运了。 Hashes and hash codes are non-unique.哈希和 hash 代码是非唯一的。

A Java String of length N has 65536 ^ N possible states, and requires an integer with 16 * N bits to represent all possible values.一个长度为 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; 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; ie the hash codes cannot be unique.即 hash 代码不能是唯一的。 This is called the Pigeonhole Principle , and there is a straight forward mathematical proof.这被称为鸽巢原理,并且有一个直接的数学证明。 (You can't fight math and win!) (你不能打数学赢!)

But if "probably unique" with a very small chance of non-uniqueness is acceptable, then crypto hashes are a good answer.但是,如果可以接受具有非常小的非唯一性的“可能是唯一的”,那么加密哈希是一个很好的答案。 The math will tell you how big (ie how many bits) the hash has to be to achieve a given (low enough) probability of non-uniqueness.数学将告诉您 hash 必须有多大(即多少位)才能实现给定(足够低)的非唯一性概率。

This is a class I use to create Message Digest hashes这是我用来创建消息摘要哈希的 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);

You can use this code for generating has code for a given string.您可以使用此代码生成给定字符串的代码。

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

I use this i tested it as key from my EhCacheManager Memory map....我使用它作为我的EhCacheManager Memory map 的密钥进行了测试。

Its cleaner i suppose我想它更干净

   /**
     * 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 "";
        }
    }

am using maven but this is the jar commons-codec-1.9.jar我正在使用 maven 但这是 jar commons-codec-1.9.jar

A few line of java code.几行 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));
}

Let's take a look at the stock hashCode() method:让我们看一下股票的 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;
}

The block of code above comes from the java.lang.String class.上面的代码块来自 java.lang.String class。 As you can see it is a 32 bit hash code which fair enough if you are using it on a small scale of data.如您所见,它是一个 32 位 hash 代码,如果您在小规模数据上使用它就足够了。 If you are looking for hash code with more than 32 bit, you might wanna checkout this link: http://www.javamex.com/tutorials/collections/strong_hash_code_implementation.shtml如果您正在寻找超过 32 位的 hash 代码,您可能想查看此链接: http://www.javamex.com/tutorials/collections/strong_hash_code_implementation.shtml

For me it worked对我来说它有效

   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