Skip to content

Commit

Permalink
Reverse int bits on big-endian system
Browse files Browse the repository at this point in the history
Fixes #1
  • Loading branch information
mwhouser committed May 22, 2013
1 parent adab9e5 commit 69ec573
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions Eleven41.Skip32/Skip32Cipher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,25 @@ public Skip32Cipher(string key, Skip32CipherKeyFormat format)
_key = bytes;
}

// IsNeedReverse
//
// Determines of the bytes of an integer need to be reversed.
private bool IsNeedReverse()
{
return !BitConverter.IsLittleEndian;
}

// Reverse
//
// Reverse a byte array
private byte[] Reverse(byte[] input)
{
byte[] result = new byte[input.Length];
for (int i = 0; i < input.Length; ++i)
result[i] = input[input.Length - i - 1];
return result;
}

/// <summary>
/// Encrypts a 32-bit integer.
/// </summary>
Expand All @@ -75,8 +94,12 @@ public Skip32Cipher(string key, Skip32CipherKeyFormat format)
public Int32 Encrypt(Int32 value)
{
byte[] input = BitConverter.GetBytes(value);
if (IsNeedReverse())
input = Reverse(input);
System.Diagnostics.Debug.Assert(input.Length == BlockSize);
byte[] result = Skip32(_key, input, 0, true);
if (IsNeedReverse())
result = Reverse(result);
return BitConverter.ToInt32(result, 0);
}

Expand Down Expand Up @@ -120,8 +143,12 @@ public byte[] Encrypt(byte[] value, int start)
public Int32 Decrypt(Int32 value)
{
byte[] input = BitConverter.GetBytes(value);
if (IsNeedReverse())
input = Reverse(input);
System.Diagnostics.Debug.Assert(input.Length == BlockSize);
byte[] result = Skip32(_key, input, 0, false);
if (IsNeedReverse())
result = Reverse(result);
return BitConverter.ToInt32(result, 0);
}

Expand Down

0 comments on commit 69ec573

Please sign in to comment.