0

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.

2
  • I'm not entirely sure what the integers are supposed to hold in your key array, I've written an answer for a byte[] instead. Just implementing an inc function should work no matter what though. Commented Nov 21, 2019 at 2:23
  • Note that this goes thourgh all possible values of the key. I'm not sure that you actually mean "permutations", that's not what your example shows anyway. Commented Nov 21, 2019 at 2:47

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

1 Comment

It's of course easy to do the same thing for an unsigned char array, no need for unsigned int type if you limit to 0..255.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.