简体   繁体   中英

Carry over incrementing bytes in an array

I'm testing to see how easily (or quickly rather) our encryption can be cracked. The encryption key is an array of byte (could be any variable length). So, starting from an array populated with all 0's, I need to increment one byte at a time starting with the first. When any byte reaches its max and goes back to 0, the next byte in the array needs to increment (carry over).

It would be simple if the array were a short fixed length - but I'm clueless how to do so in a variable array length.

Variable declared inside the thread:

FKey: array of Byte;

After each thread iteration, it calls this procedure to increment the key by one byte:

procedure TCrackThread.NextKey;
begin
  //Increment first byte
  //If max, reset to 0 and increment next byte
  //Recursively check the same for each following byte in array
end;

How can I increment (starting from the first) the bytes and carry over to the next in this variable length array?

This snippet will increase the first element and will continue to do so with the array elements as long as they are 255. If so, they are reset to zero. The routine will stop as soon as the condition is not fulfilled or the index reached maximum.

var
  k: Integer;
...
if (Length(fKey) > 0) then begin
  k := 0;
  Inc(fKey[k]);
  while (fKey[k] = 255) do begin
    fKey[k] := 0;
    Inc(k);
    if (k >= Length(fKey)) then
      break;
    Inc(fKey[k]);
  end;
end;

This would convert an array 254,0,0 into 0,1,0

If you want a carry to ripple through before the first increment, this code will do that:

procedure Next;
var
  k: Integer;
  carry: Boolean;
begin
  if (Length(fKey) > 0) then begin
    k := 0;
    repeat
      carry := (fKey[k] = 255);
      if carry then begin
        fKey[k] := 0;
        Inc(k);
        if (k >= Length(fKey)) then
          break;
      end
      else
        Inc(fKey[k]);
    until not carry;
  end;
end;

This will convert 255,255,0 into 0,0,1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM