online hash code can be obtained from this site with SHA256.
https://emn178.github.io/online-tools/sha256.html
The hash code of 1 is "6b86b273ff34fce19d6b804eff5a3f5747ada4eaa22f1d49c01e52ddb7875b4b"
but if we make the hash code input type of 1 hex, "4bf5122f344554c53bde2ebb8cd2b7e3d1600ad631c385a5d7cce23c7785459a" comes out.
I can do the first one in c# code, but I couldn't find a c# code that can do the second one. Could you help?
static string ComputeSha256Hash(string rawData)
{
// Create a SHA256
using (SHA256 sha256Hash = SHA256.Create())
{
// ComputeHash - returns byte array
byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(rawData));
// Convert byte array to a string
StringBuilder builder = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
builder.Append(bytes[i].ToString("x2"));
}
return builder.ToString();
}
}
Please try this, the key is convert hex to bytes.
public static byte[] StringToByteArray(string hex)
{
int len = hex.Length;
//the stackoverflow answer assumes you have even length,
//so I insert a 0 if odd length.
if (len % 2 == 1)
{
hex = hex.Insert(0, "0");
}
return Enumerable.Range(0, len)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
static string ComputeSha256Hash(string rawData)
{
using (SHA256 sha256Hash = SHA256.Create())
{
byte[] bytes = sha256Hash.ComputeHash(StringToByteArray(rawData));
StringBuilder builder = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
builder.Append(bytes[i].ToString("x2"));
}
return builder.ToString();
}
}
static void Main(string[] args)
{
string hash = ComputeSha256Hash("1");
Console.WriteLine(hash);
Console.ReadKey();
}
Related
This is kind of driving me nuts. I have this code in C# which I'm trying to translate to python, but for some reason I can't get the same hash.
using System.Text;
using System.Security.Cryptography;
public class Program
{
public static void Main()
{
// input, plain text here
string key = "8ea79bcec3d54597efe186780a835c075400623a11481d3d17dd92e905dbb615";
string tokenHash = "st=1585258906~exp=1585261006~acl=*";
string encoded;
HMACSHA256 hmac = new HMACSHA256(ParseHexBinary(key));
byte[] bytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(tokenHash.ToString()));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
sb.Append(bytes[i].ToString("x2"));
}
encoded = sb.ToString();
Console.WriteLine(encoded);
}
private static int HexToBinFn(char c)
{
if ('0' <= c && c <= '9')
{
return c - '0';
}
char c2 = 'A';
if ('A' > c || c > 'F')
{
c2 = 'a';
if ('a' > c || c > 'f')
{
return -1;
}
}
return (c - c2) + 10;
}
public static byte[] ParseHexBinary(String str)
{
int length = str.Length;
byte[] bytes = new byte[(length / 2)];
for (int i = 0; i < length; i += 2)
{
int bin1 = HexToBinFn(str[i]);
int bin2 = HexToBinFn(str[i + 1]);
int i2 = (bin1 * 16) + bin2;
byte b = (byte)i2;
bytes[i / 2] = b;
}
return bytes;
}
}
With C# I get this hash : 988b6a86f25529ad8a8c2da42bf95a0ca24ea113fb05fcb6e356096852693dda
This is the python code I have:
import hashlib
import hmac
import base64
key = '8ea79bcec3d54597efe186780a835c075400623a11481d3d17dd92e905dbb615'
tokenHash = 'st=1585258906~exp=1585261006~acl=*'
x = hmac.new(key.encode('utf-8'), tokenHash.encode('utf-8'), hashlib.sha256).hexdigest()
With python I get this hash: 8cbb2096d5e201454bb6797b4689a524d2d7d1def51c4b66ec6b1e4a99a509cf
Can anybody tell me please where the difference is? I can't figure out how to translate it. Thankyou so much.
I don't know what python does to the string you provide as the key to the hmac.new method, but it doesn't appear to convert the hex to bytes and that is why you're getting different hashes. If I convert the hex to bytes in python first, then they both produce the same hash.
import hashlib
import hmac
import base64
import binascii
key = '8ea79bcec3d54597efe186780a835c075400623a11481d3d17dd92e905dbb615'
keyBytes = binascii.unhexlify(key)
tokenHash = 'st=1585258906~exp=1585261006~acl=*'
x = hmac.new(keyBytes, tokenHash.encode('utf-8'), hashlib.sha256).hexdigest()
So, it would appear that they're not producing the same hash because the key is different.
If you can't modify the python code, then in C#, instead of treating key as a hex string and converting it to a byte[] you just get the UTF8 bytes of the string then they produce the same hash. For me, at least.
//var keyBytes = ParseHexBinary(key); Instead of this...
var keyBytes = Encoding.UTF8.GetBytes(key); //Do this.
I need to check for a string located inside a packet that I receive as byte array. If I use BitConverter.ToString(), I get the bytes as string with dashes (f.e.: 00-50-25-40-A5-FF).
I tried most functions I found after a quick googling, but most of them have input parameter type string and if I call them with the string with dashes, It throws an exception.
I need a function that turns hex(as string or as byte) into the string that represents the hexadecimal value(f.e.: 0x31 = 1). If the input parameter is string, the function should recognize dashes(example "47-61-74-65-77-61-79-53-65-72-76-65-72"), because BitConverter doesn't convert correctly.
Like so?
static void Main()
{
byte[] data = FromHex("47-61-74-65-77-61-79-53-65-72-76-65-72");
string s = Encoding.ASCII.GetString(data); // GatewayServer
}
public static byte[] FromHex(string hex)
{
hex = hex.Replace("-", "");
byte[] raw = new byte[hex.Length / 2];
for (int i = 0; i < raw.Length; i++)
{
raw[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
}
return raw;
}
For Unicode support:
public class HexadecimalEncoding
{
public static string ToHexString(string str)
{
var sb = new StringBuilder();
var bytes = Encoding.Unicode.GetBytes(str);
foreach (var t in bytes)
{
sb.Append(t.ToString("X2"));
}
return sb.ToString(); // returns: "48656C6C6F20776F726C64" for "Hello world"
}
public static string FromHexString(string hexString)
{
var bytes = new byte[hexString.Length / 2];
for (var i = 0; i < bytes.Length; i++)
{
bytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
}
return Encoding.Unicode.GetString(bytes); // returns: "Hello world" for "48656C6C6F20776F726C64"
}
}
string str = "47-61-74-65-77-61-79-53-65-72-76-65-72";
string[] parts = str.Split('-');
foreach (string val in parts)
{
int x;
if (int.TryParse(val, out x))
{
Console.Write(string.Format("{0:x2} ", x);
}
}
Console.WriteLine();
You can split the string at the -
Convert the text to ints (int.TryParse)
Output the int as a hex string {0:x2}
string hexString = "8E2";
int num = Int32.Parse(hexString, System.Globalization.NumberStyles.HexNumber);
Console.WriteLine(num);
//Output: 2274
From https://msdn.microsoft.com/en-us/library/bb311038.aspx
Your reference to "0x31 = 1" makes me think you're actually trying to convert ASCII values to strings - in which case you should be using something like Encoding.ASCII.GetString(Byte[])
If you need the result as byte array, you should pass it directly without changing it to a string, then change it back to bytes.
In your example the (f.e.: 0x31 = 1) is the ASCII codes. In that case to convert a string (of hex values) to ASCII values use:
Encoding.ASCII.GetString(byte[])
byte[] data = new byte[] { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x30 };
string ascii=Encoding.ASCII.GetString(data);
Console.WriteLine(ascii);
The console will display: 1234567890
My Net 5 solution that also handles null characters at the end:
hex = ConvertFromHex( hex.AsSpan(), Encoding.Default );
static string ConvertFromHex( ReadOnlySpan<char> hexString, Encoding encoding )
{
int realLength = 0;
for ( int i = hexString.Length - 2; i >= 0; i -= 2 )
{
byte b = byte.Parse( hexString.Slice( i, 2 ), NumberStyles.HexNumber, CultureInfo.InvariantCulture );
if ( b != 0 ) //not NULL character
{
realLength = i + 2;
break;
}
}
var bytes = new byte[realLength / 2];
for ( var i = 0; i < bytes.Length; i++ )
{
bytes[i] = byte.Parse( hexString.Slice( i * 2, 2 ), NumberStyles.HexNumber, CultureInfo.InvariantCulture );
}
return encoding.GetString( bytes );
}
One-liners:
var input = "Hallo Hélène and Mr. Hörst";
var ConvertStringToHexString = (string input) => String.Join("", Encoding.UTF8.GetBytes(input).Select(b => $"{b:X2}"));
var ConvertHexToString = (string hexInput) => Encoding.UTF8.GetString(Enumerable.Range(0, hexInput.Length / 2).Select(_ => Convert.ToByte(hexInput.Substring(_ * 2, 2), 16)).ToArray());
Assert.AreEqual(input, ConvertHexToString(ConvertStringToHexString(input)));
I am working on a project that ciphers a text using Position Swapping. I've completed the project using char position swapping { Hello -> elloH}, now i am working on bit position swapping. I am using the same algorithm to cipher the bits but the problem is how to change the resulting bits back to a string ?
Note:BitArray is not possible to be used.
Here is what i've got now :
static byte[] toByteArray(string s)
{
byte[] arr = new System.Text.UTF8Encoding(true).GetBytes(s);
return arr;
}// Byte Array must be changed to bits.
private void button1_Click(object sender, EventArgs e)
{
String[] X = new String[x.Length];// Will Contain the Encoded Bits
for(int i=0;i<x.Length;i++)
{
X[i] = Convert.ToString(x[i], 2);
textBox3.Text += X[i];
}
}
string str = "1000111"; //this is your string in bits
byte[] bytes = new byte[str.Length / 7];
int j = 0;
while (str.Length > 0)
{
var result = Convert.ToByte(str.Substring(0, 7), 2);
bytes[j++] = result;
if (str.Length >= 7)
str = str.Substring(7);
}
var resultString = Encoding.UTF8.GetString(bytes);
I am learning how to encode and decode string. This is a method to decode chiper text to plain text I found around the web.
public static string Decode(string chiperText)
{
byte[] numArray = Convert.FromBase64String(chiperText);
byte[] numArray1 = new byte[(int)numArray.Length - 1];
byte num = (byte)(numArray[0] ^ 188);
for (int i = 1; i < (int)numArray.Length; i++)
{
numArray1[i - 1] = (byte)(numArray[i] ^ 188 ^ num);
}
return Encoding.ASCII.GetString(numArray1);
}
My problem is I have no idea how to encode to original state. I try this method and it doesn't work.
public static string Encode(string plainText)
{
byte[] bytes = Encoding.ASCII.GetBytes(plainText);
byte[] results = new byte[(int)bytes.Length - 1];
byte num = (byte)(bytes[0] ^ 188);
for (int i = 1; i < bytes.Length; i++)
{
results[i - 1] = (byte)(bytes[i] ^ 188 ^ num);
}
return Convert.ToBase64String(results);
}
Although I agree entirely with SLaks comment that the above does not constitute any kind of crypto that you should use, the following procedure will produce the "encrypted" data that you are looking to decrypt:
public static string Encode(string plainText)
{
byte[] numArray = System.Text.Encoding.Default.GetBytes(plainText);
byte[] numArray1 = new byte[(int)numArray.Length + 1];
// Generate a random byte as the seed used
(new Random()).NextBytes(numArray1);
byte num = (byte)(numArray1[0] ^ 188);
numArray1[0] = numArray1[0];
for (int i = 0; i < (int)numArray.Length; i++)
{
numArray1[i + 1] = (byte)(num ^ 188 ^ numArray[i]);
}
return Convert.ToBase64String(numArray1);
}
Please do not, for a single second, consider using this as a method for 'encrypting' sensitive data.
I need to check for a string located inside a packet that I receive as byte array. If I use BitConverter.ToString(), I get the bytes as string with dashes (f.e.: 00-50-25-40-A5-FF).
I tried most functions I found after a quick googling, but most of them have input parameter type string and if I call them with the string with dashes, It throws an exception.
I need a function that turns hex(as string or as byte) into the string that represents the hexadecimal value(f.e.: 0x31 = 1). If the input parameter is string, the function should recognize dashes(example "47-61-74-65-77-61-79-53-65-72-76-65-72"), because BitConverter doesn't convert correctly.
Like so?
static void Main()
{
byte[] data = FromHex("47-61-74-65-77-61-79-53-65-72-76-65-72");
string s = Encoding.ASCII.GetString(data); // GatewayServer
}
public static byte[] FromHex(string hex)
{
hex = hex.Replace("-", "");
byte[] raw = new byte[hex.Length / 2];
for (int i = 0; i < raw.Length; i++)
{
raw[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
}
return raw;
}
For Unicode support:
public class HexadecimalEncoding
{
public static string ToHexString(string str)
{
var sb = new StringBuilder();
var bytes = Encoding.Unicode.GetBytes(str);
foreach (var t in bytes)
{
sb.Append(t.ToString("X2"));
}
return sb.ToString(); // returns: "48656C6C6F20776F726C64" for "Hello world"
}
public static string FromHexString(string hexString)
{
var bytes = new byte[hexString.Length / 2];
for (var i = 0; i < bytes.Length; i++)
{
bytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
}
return Encoding.Unicode.GetString(bytes); // returns: "Hello world" for "48656C6C6F20776F726C64"
}
}
string str = "47-61-74-65-77-61-79-53-65-72-76-65-72";
string[] parts = str.Split('-');
foreach (string val in parts)
{
int x;
if (int.TryParse(val, out x))
{
Console.Write(string.Format("{0:x2} ", x);
}
}
Console.WriteLine();
You can split the string at the -
Convert the text to ints (int.TryParse)
Output the int as a hex string {0:x2}
string hexString = "8E2";
int num = Int32.Parse(hexString, System.Globalization.NumberStyles.HexNumber);
Console.WriteLine(num);
//Output: 2274
From https://msdn.microsoft.com/en-us/library/bb311038.aspx
Your reference to "0x31 = 1" makes me think you're actually trying to convert ASCII values to strings - in which case you should be using something like Encoding.ASCII.GetString(Byte[])
If you need the result as byte array, you should pass it directly without changing it to a string, then change it back to bytes.
In your example the (f.e.: 0x31 = 1) is the ASCII codes. In that case to convert a string (of hex values) to ASCII values use:
Encoding.ASCII.GetString(byte[])
byte[] data = new byte[] { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x30 };
string ascii=Encoding.ASCII.GetString(data);
Console.WriteLine(ascii);
The console will display: 1234567890
My Net 5 solution that also handles null characters at the end:
hex = ConvertFromHex( hex.AsSpan(), Encoding.Default );
static string ConvertFromHex( ReadOnlySpan<char> hexString, Encoding encoding )
{
int realLength = 0;
for ( int i = hexString.Length - 2; i >= 0; i -= 2 )
{
byte b = byte.Parse( hexString.Slice( i, 2 ), NumberStyles.HexNumber, CultureInfo.InvariantCulture );
if ( b != 0 ) //not NULL character
{
realLength = i + 2;
break;
}
}
var bytes = new byte[realLength / 2];
for ( var i = 0; i < bytes.Length; i++ )
{
bytes[i] = byte.Parse( hexString.Slice( i * 2, 2 ), NumberStyles.HexNumber, CultureInfo.InvariantCulture );
}
return encoding.GetString( bytes );
}
One-liners:
var input = "Hallo Hélène and Mr. Hörst";
var ConvertStringToHexString = (string input) => String.Join("", Encoding.UTF8.GetBytes(input).Select(b => $"{b:X2}"));
var ConvertHexToString = (string hexInput) => Encoding.UTF8.GetString(Enumerable.Range(0, hexInput.Length / 2).Select(_ => Convert.ToByte(hexInput.Substring(_ * 2, 2), 16)).ToArray());
Assert.AreEqual(input, ConvertHexToString(ConvertStringToHexString(input)));