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

发布于 2024-11-10 00:53:13 字数 77 浏览 4 评论 0原文

我想为 android 中的 put 字符串生成唯一的哈希码。 是否有任何预定义库,或者我们必须手动生成。请任何人如果知道请提供链接或代码。

I wanted to generate a unique hash code for a string in put in android.
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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

你在我安 2024-11-17 00:53:13

这取决于您的意思:

  • 如前所述,String.hashCode() 为您提供 32 位哈希代码。

  • 如果您想要(例如)64 位哈希码,您可以轻松地自己实现它。

  • 如果您想要字符串的加密哈希,Java 加密库包括 MD5、SHA-1 等的实现。您通常需要将字符串转换为字节数组,然后将其提供给哈希生成器/摘要生成器。例如,请参阅 @Bryan Kemp 的回答。

  • 如果您想要一个保证唯一的哈希代码,那么您就不走运了。哈希值和哈希码不是唯一的。

长度为 N 的 Java 字符串有 65536 ^ N 个可能的状态,并且需要一个具有 16 * N 位的整数来表示所有可能的值。如果您编写一个生成较小范围(例如小于 16 * N 位)整数的哈希函数,您最终会发现多个 String 哈希为同一个整数的情况;即哈希码不能是唯一的。这称为鸽洞原理,并且有一个直接的数学证明。 (你无法与数学对抗并获胜!)

但是,如果可以接受“可能唯一”且非唯一性很小的可能性,那么加密哈希是一个很好的答案。数学将告诉您哈希必须有多大(即多少位)才能实现给定(足够低)的非唯一性概率。

It depends on what you mean:

  • As mentioned String.hashCode() gives you a 32 bit hash code.

  • If you want (say) a 64-bit hashcode you can easily implement it yourself.

  • If you want a cryptographic hash of a String, the Java crypto libraries include implementations of MD5, SHA-1 and so on. You'll typically need to turn the String into a byte array, and then feed that to the hash generator / digest generator. For example, see @Bryan Kemp's answer.

  • If you want a guaranteed unique hash code, you are out of luck. Hashes and hash codes are non-unique.

A Java String of length N has 65536 ^ N possible states, and requires an integer with 16 * N bits to represent all possible values. If you write a hash function that produces integer with a smaller range (e.g. less than 16 * N bits), you will eventually find cases where more than one String hashes to the same integer; i.e. the hash codes cannot be unique. 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 (i.e. how many bits) the hash has to be to achieve a given (low enough) probability of non-uniqueness.

书间行客 2024-11-17 00:53:13

这是我用来创建消息摘要哈希的类

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;
        }
}

This is a class I use to create Message Digest hashes

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;
        }
}
英雄似剑 2024-11-17 00:53:13
String input = "some input string";
int hashCode = input.hashCode();
System.out.println("input hash code = " + hashCode);
String input = "some input string";
int hashCode = input.hashCode();
System.out.println("input hash code = " + hashCode);
洋洋洒洒 2024-11-17 00:53:13

我用这个我测试了它作为我的 EhCacheManager 内存映射的关键....

我想它更干净

   /**
     * 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

I use this i tested it as key from my 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

友欢 2024-11-17 00:53:13

您可以使用此代码来生成给定字符串的 has 代码。

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

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);
}
[浮城] 2024-11-17 00:53:13

对我来说它有效

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

For me it worked

   public static long getUniqueLongFromString (String value){
       return  UUID.nameUUIDFromBytes(value.getBytes()).getMostSignificantBits();
    }
救赎№ 2024-11-17 00:53:13

几行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));
}

A few line of java code.

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));
}
Spring初心 2024-11-17 00:53:13

让我们看一下普通的 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 类。正如您所看到的,它是一个 32 位哈希码,如果您在小规模数据上使用它,那么它就足够了。如果您正在寻找超过 32 位的哈希码,您可能需要查看此链接:
http://www.javamex.com/tutorials/collections/strong_hash_code_implementation.shtml

Let's take a look at the stock hashCode() method:

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. 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. 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文