Question

I need to generate SecretKeySpec in Java in a specified range. e.G. I need all 16 Bit Keys. Because I need the Keys for DES , the Key-Length has to be 8 Byte. This means, the highest 6 Bytes are 0 and the lowest two bytes are store the numbers from 1 to 2^16 -1. The last hour I read a lot about bits, bytes and hex numbers that I'm really confused about all that stuff. The SecretKeySpec constructor I'd like to use is:

 public SecretKeySpec(byte[] key,
             String algorithm)

That constructor expects a byte array as a key. The way I wanted to create those 2^16 -1 byte arrays is to fill the lowest two bytes with the appropriate numbers. e.G.

  • Key 0: key[7] = 0, key[6] = 0 ... , key[0] = 0;
  • Key 1: key[7] = 0, key[6] = 0 ... , key[1] = 0 , key [0] = 1;

I'd use loops to fill the byte arrays. Is that the way I can deal with that problem?

Was it helpful?

Solution

Byte arrays default to having content with a value of zero. So you can just do:

byte[] myVeryWeakKey = new byte[8];
byte[6] = // whatever
byte[7] = //whatever

Or perhaps you want to randomly assign those last two bytes?

byte[] keybits = new byte[2];
Random r = new Random();
r.nextBytes(keybits);

System.arraycopy(keybits, 0, myVeryWeakKey, 6, 2);

I hope it goes without saying that these keys will be pitifully weak. So weak, you needn't bother with any encryption at all. (Which is why I didn't even bother to suggest SecureRandom).

If you need to create all possible values, something like the following will work:

List<byte[]> keys = new ArrayList<>();

for (int b = -128; b <= 127; b++) {
  for (int c = -128; c <= 127; c++) {
    byte[] newValue = new byte[8];
    newValue[6] = (byte) b;
    newValue[7] = (byte) c;
    keys.add(newValue);
  } 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top