I am trying to export some keys as byte[] from a HashSet to a HashMap and use the HashMap do store pairs of data. However, I am running into a problem, which is that the size om the set is larger than the size of the HashMap, for some reason. I would like to know what causes this as the HashMap is within a foreach which iterates from 0 to the size of the HashSet, namely 2^20. So, I am also expecting the size of the HashMap also to be 2^20.
So, what I am trying to store in the HashMap is two byte arrays. I am currently working with the meet-in-the-middle attack on 2DES. My encryption are properly implemented. In addition, my DES key generator is also properly implemented, so I am able to generate 2^20 keys (only 20 bits of the keys are effective). However, I when I try to put the keys in the HashMap the size is not the same as the HashSet, which doesn't make any sense.
for (int i = 0; i < Math.pow(2, 20); i++) {
possibleKeySet.add(generateDesKey());
}
for (byte[] key : possibleKeySet) {
intermediateCipher.put((encrypt(key, plainText)).toString(), key);
}
Output:
Set size: 1048576
Map size: 1048295
PS: intermediateCipher is my HashMap.
Update: I have tried to implement hashcode and equals, but i'm not sure how to implement 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?
}
}