Implementing encryption algorithms using integer keys: how to store the key during the process

StackOverflow https://stackoverflow.com/questions/20182411

  •  04-08-2022
  •  | 
  •  

Question

I am working with an encryption algorithm that uses a 4-byte key. It works like this

(pseudocode)
for i = 0 to size_of_data
   data[i] ^= key[i % 4]

   if (i % 4 == 0)
      key *= 5
      key += 2893
   end
end

So basically, everytime you reach the end of the key, you multiply the value of the key by some fixed amount before continuing with the next set of bytes.

The question I have is related to how I should be storing the key while I am decrypting the data. I can choose to store it as a byte array, which is easy to iterate through, but then it becomes a little complicated if I had to do some math operations on the byte array.

On the other hand, I can store the key as the 4-byte integer representation of the byte array, and then perform the appropriate shifting to XOR the correct byte. This makes it easy to modify the key since I'm working with an integer already.

What is a better approach to this problem? Both are valid solutions but when it comes to byte manipulation maybe there are some better approaches.

Was it helpful?

Solution

It's probably best to keep the key as an unsigned integer as you use integer operations on it. Then retrieve the values by shifting the value, e.g. data[i] ^= ((key >> ((i % 4) * 8)) & 0xFF).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top