Reputation: 11
I am trying to create all iterations for a cryptography key. I've the following code:
unsigned int key[6] = {0x0,0x0,0x0,0x0,0x0,0x0};
int count = 0;
for (int i = 0; i < 6; i++) //iterate through key
{
for (int j = 0; j < 256; j++)
{
key[i] = j;
for (int i = 0; i < 6; i++)
{
printf("%02x", key[i]);
}
printf("\n");
}
}
It only iterated through one item at a time from left to right and doesn't create all permutations i.e. if it was binary the above goes:
000 100 110 111
instead of 000 100 010 110 001 101 011 111
Is there an easy way to loop through all keys easily without tripping up over for loops? Thanks, Liam.
Upvotes: 0
Views: 47
Reputation: 93968
If you want to loop through all 2^(6*8) = 2^48 values (a very large number, mind you) the you can simply see the key as a number and then loop through all possible values by increasing the number, e.g. in Java:
/**
* Increases a number encoded as a byte array, where the byte array represents a big endian number.
*
* @param bin the binary array that needs to be increased
* @return true on carry after the maximum value has been reached
*/
private static boolean inc(byte[] bin) {
for (int i = bin.length - 1; i >= 0; i--) {
if (++bin[i] != 0) {
return false;
}
// if the binary number reaches 0 again
// we have looped and need to continue
}
// all values have become 00 now, so we have looped (a carry to the 49'th bit)
return true;
}
public static void main(String[] args) {
byte[] key = new byte[6];
do {
System.out.println(Hex.encode(key));
} while (!inc(key));
}
This is easy to replicate in C. Let i
to from 0
to bin.length - 1
if you want little endian rather than big endian.
This is also clearly shown when you show your possible values:
000 100 010 110 001 101 011 111
this is just counting, although your least significant value is at the left rather than the right.
Upvotes: 0