Hex Dump EXE File - c#

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#

Related

Program logic to calculate hexacode checksum?

I have a hexadecimal code for which I have to perform a checksum logic which will give me a checksum that will be added to the end of the Hexacode message and passed to the receiving TCP server and after that, the message I received from the server needs to be checked by performing checksum logic
Eg: I have a hexacode of 07040A13 for which checksum value is coming 58 which is added and passed as 07040A1358. In receiving I am getting 25000A01F0FFFFFFFF for this the checksum value is 64 and whole message is 25000A01F0FFFFFFFF64
The sum of this value should be 0 and the logic for checksum is (80 + Message)NOT+1 = Checksum value
And (80 + Message)Not +1 + Checksum = 0
I want this logic to be performed in C# code but I do not know where and how to start.
I have got one working solution but it is in javascript:
function calculate_checksum8(N)
{
// convert input value to upper case
strN = new String(N);
strN = strN.toUpperCase();
strHex = new String("0123456789ABCDEF");
result = 0;
fctr = 16;
for (i=0; i<strN.length; i++)
{
if (strN.charAt(i) == " ") continue;
v = strHex.indexOf(strN.charAt(i));
if (v < 0)
{
result = -1;
break;
}
result += v * fctr;
if (fctr == 16)
fctr = 1;
else
fctr = 16;
}
if (result < 0)
{
strResult = new String("Non-hex character entered");
}
else if (fctr == 1)
{
strResult = new String("Odd number of characters entered. e.g. correct value = aa aa");
}
else
{
// Calculate 2's complement
result = (~(result & 0xff) + 1) & 0xFF;
// Convert result to string
strResult = strHex.charAt(Math.floor(result/16)) + strHex.charAt(result%16);
}
return strResult;
}
public string CreateCheckSum(string hex)
{
string withchk = "80" + hex;
string strres = "";
string strHex = "0123456789ABCDEF";
int res = 0;
int fctr = 16;
for (int i = 0; i < withchk.Length; i++)
{
if (withchk[i] == ' ')
continue;
var v = strHex.IndexOf(withchk[i]);
if (v < 0)
{
res = -1;
break;
}
res += v * fctr;
if (fctr == 16)
fctr = 1;
else
fctr = 16;
}
if (res < 0)
return "Invalid";
else if (fctr == 1)
return "Invalid";
else
{
res = (~(res & 0xff) + 1) & 0xFF;
strres = strHex[(int)Math.Floor(res / 16.0)].ToString() + strHex[res % 16].ToString();
}
return strres;
}

Send binary data as parameter to a method in Web Service?

In server side (C#.NET,Windows 2003) I have a web service with a method and in client side (Visual C++ v6, WinINet, POST) I want to call that method and pass binary data as a parameter to it.
when I send Binary data an error rise and when I send ASCII data it called successful.
How can I send binary data as parameter of a method?
To send binary data to a web method you can base64 encode it and then decode it in the web service. If your variable is a byte array called data then you would do the following.
In C++ you need to create a base64 header and cpp file. The following example is from http://www.adp-gmbh.ch/cpp/common/base64.html
base64.h
#include <string>
std::string base64_encode(unsigned char const* , unsigned int len);
std::string base64_decode(std::string const& s);
base64.cpp
#include "base64.h"
#include <iostream>
static const std::string base64_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
static inline bool is_base64(unsigned char c) {
return (isalnum(c) || (c == '+') || (c == '/'));
}
std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {
std::string ret;
int i = 0;
int j = 0;
unsigned char char_array_3[3];
unsigned char char_array_4[4];
while (in_len--) {
char_array_3[i++] = *(bytes_to_encode++);
if (i == 3) {
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for(i = 0; (i <4) ; i++)
ret += base64_chars[char_array_4[i]];
i = 0;
}
}
if (i)
{
for(j = i; j < 3; j++)
char_array_3[j] = '\0';
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for (j = 0; (j < i + 1); j++)
ret += base64_chars[char_array_4[j]];
while((i++ < 3))
ret += '=';
}
return ret;
}
std::string base64_decode(std::string const& encoded_string) {
int in_len = encoded_string.size();
int i = 0;
int j = 0;
int in_ = 0;
unsigned char char_array_4[4], char_array_3[3];
std::string ret;
while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
char_array_4[i++] = encoded_string[in_]; in_++;
if (i ==4) {
for (i = 0; i <4; i++)
char_array_4[i] = base64_chars.find(char_array_4[i]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (i = 0; (i < 3); i++)
ret += char_array_3[i];
i = 0;
}
}
if (i) {
for (j = i; j <4; j++)
char_array_4[j] = 0;
for (j = 0; j <4; j++)
char_array_4[j] = base64_chars.find(char_array_4[j]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (j = 0; (j < i - 1); j++) ret += char_array_3[j];
}
return ret;
}
After you have your base64 implementation you can create the string to pass.
std::string encoded = base64_encode(data, sizeof(data));
You have to be mindful however of the fact that your data will expand by encoding it to Base64 so your uploads will take longer as the data will be larger. It will be approximately 37% larger (see the MIME section of http://en.wikipedia.org/wiki/Base64)
To decode the data on the other end you would simply do the following.
byte[] data = System.Convert.FromBase64String(yourParameterName);

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

How to convert a byte array to uint64 and back in C#?

I have been trying this for long. I have a byte array, which I want to convert to ulong and return the value to another function and that function should get the byte values back.
I tried bitshifting, but it was unsuccessfull in few cases. Is there any alternate to bitshifting? or do you have any short example? Thanks for the help.
Here is the bitshift code that I used, I don't understant why the second entry is not 00000001:
using System;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int[]responseBuffer = {0,1,2,3,4,5};
UInt64 my = (UInt64)(((UInt64)(((responseBuffer[0]) << 40) & 0xFF0000000000)) |
(UInt64)(((responseBuffer[1]) << 32) & 0x00FF00000000) |
(UInt64)(((responseBuffer[2]) << 24) & 0x0000FF000000) |
(UInt64)(((responseBuffer[3]) << 16) & 0x000000FF0000) |
(UInt64)(((responseBuffer[4]) << 8) & 0x00000000FF00) |
(UInt64)(responseBuffer[5] & 0xFF));
UInt64[] m_buffer = {(UInt64)((my >> 40) & 0xff),
(UInt64)((my >> 33) & 0xff) ,
(UInt64)((my >> 24) & 0xff) ,
(UInt64)((my>> 16) & 0xff) ,
(UInt64)((my>> 8) & 0xff) ,
(UInt64)(my& 0xff)};
Console.WriteLine("" + m_buffer[1]);
//string m_s = "";
StringBuilder sb = new StringBuilder();
for (int k = 0; k < 6; k++)
{
int value = (int)m_buffer[k];
for (int i = 7; i >= 0; i--)
{
if ((value >> i & 0x1) > 0)
{
sb.Append("1");
value &= (Byte)~(0x1 << i);
}
else
sb.Append("0");
}
sb.Append(" ");
}
Console.WriteLine(sb.ToString());
Console.Read();
}
}
}
Firstly I'd work out what went wrong with bitshifting, in case you ever needed it again. It should work fine.
Secondly, there's an alternative with BitConverter.ToUInt64 and BitConverter.GetBytes(ulong) if you're happy using the system endianness.
If you want to be able to specify the endianness, I have an EndianBitConverter class in my MiscUtil library which you could use.
(If you just need it to be reversible on the same sort of machine, I'd stick with the built in one though.)
I'm not sure what the point of the left bitshifting and right bitshifting you're doing initially.(i'm assuming you're trying to generate Uint64 values to test your function with).
To fix your function, just cast the numbers to UInt64 and then test them. Alternatively you can create long literals by using a suffix of l. such as UInt64[] responseBuffer = {0l,1l};
static void Main(string[] args)
{
int[] responseBuffer = { 0, 1, 2, 3, 4, 5 };
List<UInt64> bufferList = new List<ulong>();
foreach (var r in responseBuffer)
bufferList.Add((UInt64)r);
UInt64[] m_buffer = bufferList.ToArray();
foreach (var item in m_buffer)
Console.WriteLine(item);
//string m_s = "";
StringBuilder sb = new StringBuilder();
for (int k = 0; k < m_buffer.Length; k++)
{
int value = (int)m_buffer[k];
for (int i = 7; i >= 0; i--)
{
if ((value >> i & 0x1) > 0)
{
sb.Append("1");
value &= (Byte)~(0x1 << i);
}
else
sb.Append("0");
}
sb.Append(" ");
}
Console.WriteLine(sb.ToString());
}

Decoding Decimal64 data

I'm looking for a simple way to decode data stored in the Decimal64 format (described here: http://en.wikipedia.org/wiki/Decimal64_floating-point_format) using C#.
Any thoughts?
Looked everywhere for it, finally we implemented it ourselves.
Update
Some of you has asked us for the code - here is our code for it, We call it Float Decimal, I think it matches what Decimal 64 does - but no guarantees - please check for yourself.
Also note - that the value of _size should be 8.
if (bytes[0] == 0) return 0;
var s = "";
for (var i = 1; i < bytes.Length; i++)
s += bytes[i].ToString("X").PadLeft(2, '0');
return decimal.Parse("." + s.TrimEnd('0')) * (decimal)Math.Pow(10 , ((bytes[0] & ~128) - 64)) * ((bytes[0] & 128) > 0 ? -1 : 1);
To save:
if (value != 0)
{
var negative = value < 0;
var s = value.ToDecimal().ToString(CultureInfo.InvariantCulture).TrimStart('-', '0');
var i = s.IndexOf('.');
if (i >= 0)
{
s = s.Remove(i, 1);
if (i == 0)
{
i = s.Length;
s = s.TrimStart('0');
i = s.Length-i;
}
}
else i = s.Length;
bytes[0] = (byte)(64 + i + (negative ? 128 : 0));
s = s.PadRight((_size - 1) * 2, '0');
for (var j = 1; j < _size && (j - 1) * 2 < s.Length; j++)
bytes[j] = byte.Parse(s.Substring((j - 1) * 2, 2), System.Globalization.NumberStyles.HexNumber);
}
Read a bit too fast there.
I think you'd want to have a look at the BitConverter.ToSingle method in C# but reverse the order of the bytes to get a correct result. :)
B.R
Jaggernauten

Categories