Trouble with bitshift operations - c#

I try to realize hashing from local standart.
But it return wrong results in simple shift functions. I tried shift message:
byte[] test = Hash.StringToByteArrayFastest("EFCDAB8967452301");
Console.WriteLine(ToHex(Hash.ShLo(test)));
Console.WriteLine(ToHex(Hash.ShHi(test)));
And I expect to get:
ShLo : 77E6D5C4B3A2918016
ShHi : DF9B5712CE8A460216
but get this:
ShLo : f7e6d5c4b3a29100
ShHi : de9b5713cf8a4602
Here's my code
public static byte[] ShHi(byte[] B)
{
return BitConverter.GetBytes(BitConverter.ToUInt64(B, 0) << 1);
}
public static byte[] ShLo(byte[] B)
{
return BitConverter.GetBytes(BitConverter.ToUInt64(B, 0) >> 1);
}
public static byte[] StringToByteArrayFastest(string hex)
{
if (hex.Length % 2 == 1)
throw new Exception("The binary key cannot have an odd number of digits");
byte[] arr = new byte[hex.Length >> 1];
for (int i = 0; i < hex.Length >> 1; ++i)
{
arr[i] = (byte)((GetHexVal(hex[i << 1]) << 4) + (GetHexVal(hex[(i << 1) + 1])));
}
return arr;
}
public static int GetHexVal(char hex)
{
int val = (int)hex;
return val - (val < 58 ? 48 : 55);
}
public static string ToHex(byte[] bytes)
{
char[] c = new char[bytes.Length * 2];
byte b;
for (int bx = 0, cx = 0; bx < bytes.Length; ++bx, ++cx)
{
b = ((byte)(bytes[bx] >> 4));
c[cx] = (char)(b > 9 ? b + 0x37 + 0x20 : b + 0x30);
b = ((byte)(bytes[bx] & 0x0F));
c[++cx] = (char)(b > 9 ? b + 0x37 + 0x20 : b + 0x30);
}
return new string(c);
}

public static string ToHex(byte[] bytes)
{
char[] c = new char[bytes.Length * 2];
byte b;
for (int bx = 0, cx = c.Length - 1; bx < bytes.Length; ++bx)
{
b = ((byte)(bytes[bx] & 0x0F));
c[cx--] = (char)(b > 9 ? b + 0x37 + 0x20 : b + 0x30);
b = ((byte)(bytes[bx] >> 4));
c[cx--] = (char)(b > 9 ? b + 0x37 + 0x20 : b + 0x30);
}
return new string(c);
}
public static byte[] StringToByteArrayFastest(string hex)
{
if (hex.Length % 2 == 1) throw new Exception("The binary key cannot have an odd number of digits");
byte[] arr = new byte[hex.Length >> 1];
for (int i = 0, j = arr.Length - 1; i < arr.Length; ++i)
{
arr[j--] = (byte)((GetHexVal(hex[i << 1]) << 4) + (GetHexVal(hex[(i << 1) + 1])));
}
return arr;
}

Related

Hex Dump EXE File

How do I properly display the contents of an EXE file "C:/Path/To/File.exe" in hexadecimal form? So far, I have:
byte[] BytArr = File.ReadAllBytes("C:/Path/To/File.exe")
I tried using a switch statement (not shown here) that reads every few bytes and should output the appropriate hexadecimal code, but it failed. What should I do? I would really appreciate it if anyone can help me.
Beware that the answer code isn't well formatted and is rather inefficient (source: https://www.codeproject.com/articles/36747/quick-and-dirty-hexdump-of-a-byte-array), but I did make an effort to format it properly.
Answer Code:
using System.Text;
namespace HexDump
{
class Utils
{
public static string HexDump(byte[] bytes, int bytesPerLine = 16)
{
if (bytes == null) return "<null>";
int bytesLength = bytes.Length;
char[] HexChars = "0123456789ABCDEF".ToCharArray();
int firstHexColumn =
8 // 8 characters for the address
+ 3; // 3 spaces
int firstCharColumn = firstHexColumn
+ bytesPerLine * 3 // - 2 digit for the hexadecimal value and 1 space
+ (bytesPerLine - 1) / 8 // - 1 extra space every 8 characters from the 9th
+ 2; // 2 spaces
int lineLength = firstCharColumn
+ bytesPerLine // - characters to show the ascii value
+ Environment.NewLine.Length; // Carriage return and line feed (should normally be 2)
char[] line = (new String(' ', lineLength - Environment.NewLine.Length) + Environment.NewLine).ToCharArray();
int expectedLines = (bytesLength + bytesPerLine - 1) / bytesPerLine;
StringBuilder result = new StringBuilder(expectedLines * lineLength);
for (int i = 0; i < bytesLength; i += bytesPerLine)
{
line[0] = HexChars[(i >> 28) & 0xF];
line[1] = HexChars[(i >> 24) & 0xF];
line[2] = HexChars[(i >> 20) & 0xF];
line[3] = HexChars[(i >> 16) & 0xF];
line[4] = HexChars[(i >> 12) & 0xF];
line[5] = HexChars[(i >> 8) & 0xF];
line[6] = HexChars[(i >> 4) & 0xF];
line[7] = HexChars[(i >> 0) & 0xF];
int hexColumn = firstHexColumn;
int charColumn = firstCharColumn;
for (int j = 0; j < bytesPerLine; j++)
{
if (j > 0 && (j & 7) == 0) hexColumn++;
if (i + j >= bytesLength)
{
line[hexColumn] = ' ';
line[hexColumn + 1] = ' ';
line[charColumn] = ' ';
}
else
{
byte b = bytes[i + j];
line[hexColumn] = HexChars[(b >> 4) & 0xF];
line[hexColumn + 1] = HexChars[b & 0xF];
line[charColumn] = (b < 32 ? 'ยท' : (char)b);
}
hexColumn += 3;
charColumn++;
}
result.Append(line);
}
return result.ToString();
}
}
}
Here's some simple code that will lump the bytes 4 at a time(step) with a space delimiter(delimiter):
int step = 4;
string delimiter = " ";
for(int i = 0; i < BytArr.Length;i += step)
{
for(int j = 0; j < step; j++)
{
Console.Write(BytArr[i + j].ToString("X2"));
}
Console.Write(delimiter);
}
URL shows how to dump in C. Search for C sample which is given towards the end of the page.
This URL shows example in C#

Convert a hex string (byte list) to a byte array

I want to convert a string ("00812B1FA4BEA310199D6E00DD010F5402000001807") to a byte array.
But I want each digit of the string to be the hex value.
Expected result:
array[0] = 0x00;
array[1] = 0x81;
array[0] = 0x2B;
array[0] = 0x1F;
etc...
I tried several methods. None gave the expected result. The closest ones were:
private static byte[] Convert(string tt)
{
byte[] bytes2 = new byte[tt.Length];
int i = 0;
foreach ( char c in tt)
{
bytes2[i++] = (byte)((int)c - 48);
}
return bytes2;
}
public static byte[] ConvertHexStringToByteArray(string hexString)
{
byte[] HexAsBytes = new byte[hexString.Length / 2];
for (int index = 0; index < HexAsBytes.Length; index++)
{
string byteValue = hexString.Substring(index * 2, 2);
byte[] a = GetBytes(byteValue);
HexAsBytes[index] = a[0];
}
return HexAsBytes;
}
Found solution here: How do you convert Byte Array to Hexadecimal String, and vice versa?
( answer starting by Inverse function for Waleed Eissa code)
Difficult to find because the thread has 36 answers.
public static byte[] HexToBytes(string hexString)
{
byte[] b = new byte[hexString.Length / 2];
char c;
for (int i = 0; i < hexString.Length / 2; i++)
{
c = hexString[i * 2];
b[i] = (byte)((c < 0x40 ? c - 0x30 : (c < 0x47 ? c - 0x37 : c - 0x57)) << 4);
c = hexString[i * 2 + 1];
b[i] += (byte)(c < 0x40 ? c - 0x30 : (c < 0x47 ? c - 0x37 : c - 0x57));
}
return b;
}
You can use Convert.ToByte to convert 2 hexadecimal chars to byte.
public static byte[] HexToByteArray(string hexstring)
{
var bytes = new List<byte>();
for (int i = 0; i < hexstring.Length/2; i++)
bytes.Add(Convert.ToByte("" + hexstring[i*2] + hexstring[i*2 + 1], 16));
return bytes.ToArray();
}

Feistel Cipher in c#

I'm trying to implement a Feistel Cipher, I have the following code:
public static byte[] Encode(byte[] bytes) {
byte[] s = (byte[])bytes.Clone();
int half = s.Length / 2;
if (s.Length % 2 != 0)
throw new Exception("Unbalanced code");
byte[] left = new byte[half];
byte[] right = new byte[half];
Array.Copy(s, left, half);
Array.Copy(s, half, right, 0, half);
for (var k = 0; k < ROUNDS; k++) {
left = XOR(left,f(right));
var temp = left; left = right; right = temp;
}
byte[] toReturn = new byte[s.Length];
Array.Copy(left, 0, toReturn, half, half);
Array.Copy(right, 0, toReturn, 0, half);
return toReturn;
}
In this sample, ROUNDS is 21 and f is a function that rearranges the bytes in an array of bytes.
Unfortunately, while bytes should be equal to Encode(Encode(bytes)), it's not. And I have no idea what I'm doing wrong.
Any advice?
Edit: The code for f()
public static byte[] f(byte[] s) {
byte[] toReturn = (byte[])s.Clone();
byte temp = s[0];
for (var k = 1; k < s.Length; k++) {
s[k-1] = s[k];
s[k - 1] = (byte)(s[k - 1] ^ 45);
}
s[s.Length - 1] = temp;
s[s.Length - 1] = (byte)(s[s.Length - 1] ^ 45);
return toReturn;
}
CodesInChaos is correct, the problem was the variable being mutated.

Faster way to swap endianness in C# with 32 bit words

In this question, the following code:
public static void Swap(byte[] data)
{
for (int i = 0; i < data.Length; i += 2)
{
byte b = data[i];
data[i] = data[i + 1];
data[i + 1] = b;
}
}
was rewritten in unsafe code to improve its performance:
public static unsafe void SwapX2(Byte[] Source)
{
fixed (Byte* pSource = &Source[0])
{
Byte* bp = pSource;
Byte* bp_stop = bp + Source.Length;
while (bp < bp_stop)
{
*(UInt16*)bp = (UInt16)(*bp << 8 | *(bp + 1));
bp += 2;
}
}
}
Assuming that one wanted to do the same thing with 32 bit words:
public static void SwapX4(byte[] data)
{
byte temp;
for (int i = 0; i < data.Length; i += 4)
{
temp = data[i];
data[i] = data[i + 3];
data[i + 3] = temp;
temp = data[i + 1];
data[i + 1] = data[i + 2];
data[i + 2] = temp;
}
}
how would this be rewritten in a similar fashion?
public static unsafe void SwapX4(Byte[] Source)
{
fixed (Byte* pSource = &Source[0])
{
Byte* bp = pSource;
Byte* bp_stop = bp + Source.Length;
while (bp < bp_stop)
{
*(UInt32*)bp = (UInt32)(
(*bp << 24) |
(*(bp + 1) << 16) |
(*(bp + 2) << 8) |
(*(bp + 3) ));
bp += 4;
}
}
}
Note that both of these functions (my SwapX4 and your SwapX2) will only swap anything on a little-endian host; when run on a big-endian host, they are an expensive no-op.
This version will not exceed the bounds of the buffer. Works on both Little and Big Endian architectures. And is faster on larger data. (Update: Add build configurations for x86 and x64, predefine X86 for 32 bit(x86) and X64 for 64 bit(x64) and it'll be slightly faster.)
public static unsafe void Swap4(byte[] source)
{
fixed (byte* psource = source)
{
#if X86
var length = *((uint*)(psource - 4)) & 0xFFFFFFFEU;
#elif X64
var length = *((uint*)(psource - 8)) & 0xFFFFFFFEU;
#else
var length = (source.Length & 0xFFFFFFFE);
#endif
while (length > 7)
{
length -= 8;
ulong* pulong = (ulong*)(psource + length);
*pulong = ( ((*pulong >> 24) & 0x000000FF000000FFUL)
| ((*pulong >> 8) & 0x0000FF000000FF00UL)
| ((*pulong << 8) & 0x00FF000000FF0000UL)
| ((*pulong << 24) & 0xFF000000FF000000UL));
}
if(length != 0)
{
uint* puint = (uint*)psource;
*puint = ( ((*puint >> 24))
| ((*puint >> 8) & 0x0000FF00U)
| ((*puint << 8) & 0x00FF0000U)
| ((*puint << 24)));
}
}
}

This code in VB net

I have decompiled an vb.net application with reflector
All string are encrypted with this method:
Public Shared Function smethod_0(ByVal string_0 As String) As String
Dim length As Integer = string_0.Length
Dim chArray As Char() = New Char(length - 1) {}
Dim i As Integer
For i = 0 To chArray.Length - 1
Dim ch As Char = string_0.Chars(i)
Dim num3 As Byte = CByte((ch Xor (length - i)))
Dim num4 As Byte = CByte(((ch >> 8) Xor i))
chArray(i) = DirectCast(((num4 << 8) Or num3), Char)
Next i
Return String.Intern(New String(chArray))
End Function
This method receives an input string like this:
"j" & ChrW(354) & ChrW(623) & ChrW(868)
and returns a readable string.
How can I convert this code in vb.net or c#?
The Vb.net compiler complains that this code is not correcte because xor is not defined for a char/int combination.
C# version (only for educational reasons - keeping similar code as possible):
public static string encrypt(string s)
{
int length = s.Length, i = 0;
char[] chArray = new char[length];
byte b1, b2;
char ch;
for (i = 0; i <= chArray.Length - 1; i++)
{
ch = s[i];
b1 = Convert.ToByte((ch ^ (length - i)));
b2 = Convert.ToByte(((ch >> 8) ^ i));
chArray[i] = (char)((b2 << 8) | b1);
}
return string.Intern(new string(chArray));
}
I have resolved in this way:
public static string encrypt(string string_0)
{
int length = string_0.Length;
char[] chArray = new char[length];
for (int i = 0; i < chArray.Length; i++)
{
char ch = string_0[i];
byte num3 = (byte)(ch ^ (length - i));
byte num4 = (byte)((ch >> 8) ^ i);
chArray[i] = (char)((num4 << 8) | num3);
}
File.AppendAllText("decript.txt", Environment.NewLine + string_0 + " = " + string.Intern(new string(chArray)));
return string.Intern(new string(chArray));
}
Thanks for help

Categories