I am developing an Envelope encryption library where envelope structure is combination of byte arrays.
keyAlias length , keyAlias , IVBytes, cipherBytes =
[int][keyAlias][IV][cipherBytes]
As I am storing first 4 bytes of int to retrieve the length of keyAlias from envelope bytes, looking for correct handling of int to bytes and back to int.
Assumptions : I have decide to always store int bytes in Little-Endian format in envelope bytes.
Does below method for int to bytes correct. I have no way to test it as not having access to Big-Endian machine.
[Fact]
public void IntToByteConverion_ShouldConvertBack2()
{
var intBytes = 2.ToLittleEndianBytes();
//Store intBytes to Database or AWS S3
// Retrive back the bytearray and convert to int32.
int intValue = intBytes.FromLittleEndianBytes();
Assert.Equal(2, intValue);
}
public static byte[] ToLittleEndianBytes(this int value)
{
if (BitConverter.IsLittleEndian)
return BitConverter.GetBytes(value);
else
{
var bigEndianBytes = BitConverter.GetBytes(value);
Array.Reverse(bigEndianBytes);// Converted to LittleEndian
return bigEndianBytes;
}
}
public static Int32 FromLittleEndianBytes(this byte[] littleEndianBytes)
{
if (BitConverter.IsLittleEndian)
return BitConverter.ToInt32(littleEndianBytes, 0);
else
{
Array.Reverse(littleEndianBytes);// Converted to big endian as machine CPU is big endian
return BitConverter.ToInt32(littleEndianBytes, 0);
}
}