我正在尝试从一个HashSet中将一些密钥导出为byte[],并使用HashMap存储数据对。然而,我遇到了一个问题,就是HashSet的大小比HashMap的大小要大,原因不明。我想知道是什么原因导致了这种情况,因为HashMap在foreach循环中,迭代从0到HashSet的大小,即2^20。因此,我也期望HashMap的大小也是2^20。
所以,我要在HashMap中存储两个字节数组。我目前正在处理2DES的meet-in-the-middle攻击。我的加密已经正确实现。此外,我的DES密钥生成器也已经正确实现,所以我能够生成2^20个密钥(只有20位是有效的)。然而,当我尝试将密钥放入HashMap时,其大小与HashSet的大小不同,这没有任何意义。
所以,我要在HashMap中存储两个字节数组。我目前正在处理2DES的meet-in-the-middle攻击。我的加密已经正确实现。此外,我的DES密钥生成器也已经正确实现,所以我能够生成2^20个密钥(只有20位是有效的)。然而,当我尝试将密钥放入HashMap时,其大小与HashSet的大小不同,这没有任何意义。
for (int i = 0; i < Math.pow(2, 20); i++) {
possibleKeySet.add(generateDesKey());
}
for (byte[] key : possibleKeySet) {
intermediateCipher.put((encrypt(key, plainText)).toString(), key);
}
输出:
集合大小:1048576
映射大小:1048295
PS:intermediateCipher是我的HashMap。
更新: 我已经尝试实现了hashcode和equals,但我不确定如何实现hashcode。
class ByteArray {
private byte[] key;
ByteArray(byte[] key) {
this.key = key;
}
byte[] getKey() {
return key;
}
public boolean equals(Object obj) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(obj);
oos.writeObject(obj);
oos.flush();
byte [] data = bos.toByteArray();
return key.equals(data);
}
public int hashCode() {
// what should I write here?
}
}
put
方法的返回值来检查它。如果没有发生冲突,它将返回null。 - ByeBye(encrypt(key, plainText)
this will probably produce duplicates. You can check it by addingif(putReturn != null) sysout(putReturn)
- ByeByeintermediateCipher.put((encrypt(key, plainText)).toString(), key);
的返回值。 - ByeByebyte[]
作为密钥……因此会出现重复。 - Stephen C