在我们的应用程序中,我们从java对象生成hashcode并将其存储在某个级别的数据库中。 现在我的问题是,如果有人手动生成一个数字,是否有一种方法可以确定它是否是由JVM从对象创建的有效哈希码而不是手动创建的。
答案 0 :(得分:3)
不,没有 - 至少如果它落在int
的范围内。 任何 int都是有效的哈希码。特别是,对于任何int值x,都是new Integer(x) == x
的散列。
答案 1 :(得分:3)
如果要在数据库中保留对象的“签名”,请使用其他函数。 hashCode的设计难以猜测或反向工程。
因为你使用了hashCode,我假设你不关心具有相同的F(X)= F(Y),其中X和Y是不同的对象。
如果确实如此,请考虑使用散列函数,可能加一些“秘密”盐。 例如:
public static String signature(Object o)
{
StringBuffer sb = new StringBuffer();
try
{
MessageDigest md5 = MessageDigest.getInstance("md5");
String st = "SECRET!!1" + o.hashCode();
md5.update(st.getBytes());
sb.append(getHexString(md5.digest()));
}
catch (NoSuchAlgorithmException e)
{
throw new RuntimeException("bah");
}
catch (UnsupportedEncodingException e)
{
throw new RuntimeException("bah2");
}
return sb.toString();
}
static final byte[] HEX_CHAR_TABLE =
{
(byte) '0', (byte) '1', (byte) '2', (byte) '3',
(byte) '4', (byte) '5', (byte) '6', (byte) '7',
(byte) '8', (byte) '9', (byte) 'a', (byte) 'b',
(byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f'
};
public static String getHexString(byte[] raw) throws UnsupportedEncodingException
{
byte[] hex = new byte[2 * raw.length];
int index = 0;
for (byte b : raw)
{
int v = b & 0xFF;
hex[index++] = HEX_CHAR_TABLE[v >>> 4];
hex[index++] = HEX_CHAR_TABLE[v & 0xF];
}
return new String(hex, "ASCII");
}
答案 2 :(得分:1)
没有。基本的hashCode()操作可以自由地返回任何int,只要它是一致的。我认为真正的问题是你想做什么?
答案 3 :(得分:1)
没有办法找到这个。