如何为android中的字符串输入生成唯一的哈希码...? [英] How to generate a unique hash code for string input in android...?
问题描述
我想为 android 中的字符串生成一个唯一的哈希码.是否有任何预定义的库,或者我们必须手动生成.请任何知道的人提供链接或代码.
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.
推荐答案
这取决于你的意思:
如前所述,
String.hashCode()
为您提供 32 位哈希码.
As mentioned
String.hashCode()
gives you a 32 bit hash code.
如果您想要(比如说)一个 64 位哈希码,您可以自己轻松实现.
If you want (say) a 64-bit hashcode you can easily implement it yourself.
如果您想要字符串的加密哈希,Java 加密库包括 MD5、SHA-1 等的实现.您通常需要将字符串转换为字节数组,然后将其提供给哈希生成器/摘要生成器.例如,请参阅@Bryan Kemp 的回答.
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.
长度为 N 的 Java 字符串具有 65536 ^ N
个可能的状态,并且需要一个具有 16 * N
位的整数来表示所有可能的值.如果你写了一个哈希函数,它产生的整数范围更小(例如,小于 16 * N
位),你最终会发现多个 String 哈希到同一个整数的情况;即哈希码不能是唯一的.这被称为鸽洞原理,并且有一个直接的数学证明.(你不能打数学赢!)
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.
这篇关于如何为android中的字符串输入生成唯一的哈希码...?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!