Search code examples
c#securitybitwise-operatorsbinary-reproducibility

How to produce 8 bytes from 4 bytes with a reproducible operation?


I've 4 bytes of data and need an 8 bytes array for a security operation. I should produce these 8 bytes form the 4 bytes byte array and this should be reproducible.

I was thinking of using exact byte array and adding 4 extra bytes and fill them with AND, OR, XOR... of the initial array in a known sequence. I'm not sure if it's a good idea. I just need an 8 byte array from this 4 bytes and the operation should be reproducible (same 8 bytes with same given 4 bytes). Please give an example in C#


Solution

  • Why not just pad the existing 4 bytes with another 4 bytes of zeroes? Or repeat the original 4 bytes. For example:

    static byte[] Pad(byte[] input)
    {
        // Alternatively use Array.Resize
        byte[] output = new byte[input.Length + 4];
        Buffer.BlockCopy(input, 0, output, 0, input.Length);
        return output;
    }
    
    static byte[] Repeat(byte[] input)
    {
        byte[] output = new byte[input.Length * 2];
        Buffer.BlockCopy(input, 0, output, 0, input.Length);
        Buffer.BlockCopy(input, 0, output, input.Length, input.Length);
        return output;
    }
    

    Both of these fulfil your original criteria, I believe... but I suspect you're looking for something else. If that's the case, you need to be explicit about what you need.

    EDIT: As I've said in the comments, you're basically not adding any real security here - padding will make that clearer, IMO. On the other hand, if you do want some security-through-obscurity, you could find a random number generator that allows seeding, and use that as a starting point. For example:

    // Don't use this - see below. Just the concept...
    int seed = BitConverter.ToInt32(input, 0); // TODO: Cope with endianness
    Random rng = new Random(seed);
    byte[] output = new byte[8];
    Buffer.BlockCopy(input, 0, output, 0, 4);
    for (int i = 4; i < 8; i++) {
        output[i] = (byte) rng.Next(256);
    }
    

    Now, the reason I've got the comment above is that you probably need an algorithm which is guaranteed not to change between versions of .NET. Find code to something like the Mersenne Twister, for exmaple.