get double hash result like js-sha1 library in c# - c#

I try to hash a double (1529480427715.5532) with SHA1 algorithm and i have this hash in c#:
use in string format: "3e8f41233f90a85f9963afaa571ba76afb8bb08d"
use in double format: "c880857c399c7b9cc9c6395197e700543c400b17"
but in fact i want to get this hash "da39a3ee5e6b4b0d3255bfef95601890afd80709" as result like when i'm using js-sha1 library.

Given this code to convert from float64 (that is double in C#) to Uint8array, you can:
// c880857c399c7b9cc9c6395197e700543c400b17
var hash = sha1(convertTypedArray(new Float64Array([1529480427715.5532]), Uint8Array));
or even shorter, without using that link, because sha1 accepts ArrayBuffer as a parameter:
var hash = sha1(new Float64Array([1529480427715.5532]).buffer);
Note that sha1 accepts only some types of input, number isn't one of them.
From the examples of the library it seems strings, Array, Uint8Array, ArrayBuffer are supported.
As written by #Freggar,
// da39a3ee5e6b4b0d3255bfef95601890afd80709
var hash = sha1('');
And, using strings:
// 3e8f41233f90a85f9963afaa571ba76afb8bb08d
var hash = sha1('1529480427715.5532');

Related

How to compare effectively two SHA512Managed hash values

I use SHA512Managed class for coding user password string. I initually create etalon string coded in the folowing way:
Convert password string (for example "Johnson_#1") to byte array;
Get hash value of this byte array using SHA512Managed.ComputeHash
method. As you know, hash value gotten from SHA512Managed.ComputeHash(byte[])
method is byte array too.
Then (in program loop) I convert this hash byte array to string in the following way:
System.Text.StringBuilder sBuilder = new System.Text.StringBuilder();
for (int i = 0; i < passwordСache.Length; i++)
{
sBuilder.Append(passwordСache[i].ToString("x2"));
}
string passwordCacheString = sBuilder.ToString();
where the passwordСache is hash byte array and passwordCacheString is result string.
Finally, I store result string in MS SQL Server database table as etalon string.
The matter is in the folowing: If I periodically call SHA512Managed.ComputeHash(byte[]) method and each time pass to it the same byte array as input parameter (for example obtained from "Johnson_#1" string), then the content of returned hash byte array will differs from time to time.
So, if I convert such hash byte array to string (as I showed above) and compare this string to etalon string that is in database table, then the content of this string will differ from content of etalon string though the same string ("Johnson_#1") underlies.
Better defined the question
My question is: Is there a way of determining that two compared SHA512Managed hash byte arrays with different content were created on the base of the same string? Yuor help will be appreciated highly.
As xanatos mentioned in his comments, hash functions must be deterministic.
That is for the same input, you'll get the same hash output.
Try it for yourself:
SHA512Managed sha512Managed = new SHA512Managed();
for (int i = 0; i < 1000; i++) {
var input = Guid.NewGuid().ToString();
byte[] data = sha512Managed.ComputeHash(Encoding.UTF8.GetBytes(input));
byte[] data2 = sha512Managed.ComputeHash(Encoding.UTF8.GetBytes(input));
if (Encoding.UTF8.GetString(data) != Encoding.UTF8.GetString(data2)) {
throw new InvalidOperationException("Hash functions as we know them are useless");
}
}

xxHash convert resulting in hash too long

I'm using xxHash for C# to hash a value for consistency.
ComputeHash returns a byte[], but I need to store the results in a long.
I'm able to convert the results into an int32 using the BitConverter. Here is what I've tried:
var xxHash = new System.Data.HashFunction.xxHash();
byte[] hashedValue = xxHash.ComputeHash(Encoding.UTF8.GetBytes(valueItem));
long value = BitConverter.ToInt64(hashedValue, 0);
When I use int this works fine, but when I change to ToInt64 it fails.
Here's the exception I get:
Destination array is not long enough to copy all the items in the collection. Check array index and length.
When you construct your xxHash object, you need to supply a hashsize:
var hasher = new xxHash(32);
valid hash sizes are 32 and 64.
See https://github.com/brandondahler/Data.HashFunction/blob/master/src/xxHash/xxHash.cs for the source.
Adding a new answer because current implementation of xxHash from Brandon Dahler uses a hashing factory where you initialize the factory with a configuration containing hashsize and seed:
using System.Data.HashFunction.xxHash;
//can also set seed here, (ulong) Seed=234567
xxHashConfig config = new xxHashConfig() { HashSizeInBits = 64 };
var factory = xxHashFactory.Instance.Create(config);
byte[] hashedValue = factory.ComputeHash(Encoding.UTF8.GetBytes(valueItem)).Hash;
BitConverter.ToInt64 expects hashedValue to have 8 bytes (= 64bits). You could manually extend, and then pass it.

C# MD5 hash not matches Java / PHP MD5 hash

My exercise is to port an administration-backend from php to .net.
The backend communicates with an app written in java.
Some things compared with md5-hashes, in php and java the md5 hashes are equally.
I cannot change the md5 hash-code in the java app, because then will over 10k customer cards not work.
My problem is, the backend is ported and now the communication between the new backend (.net) and the java app.
My .net md5-hash code returns not the same hash as the java code.
java:
public static String getMD5(String input) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] messageDigest = md.digest(input.getBytes());
BigInteger number = new BigInteger(1, messageDigest);
String hashtext = number.toString(16);
// Now we need to zero pad it if you actually want the full 32 chars.
while (hashtext.length() < 32)
hashtext = "0" + hashtext;
return hashtext;
}
catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
and my .net code:
public String hashMD5(String wert)
{
byte[] asciiBytes = ASCIIEncoding.UTF8.GetBytes(wert);
byte[] hashedBytes = MD5CryptoServiceProvider.Create().ComputeHash(asciiBytes);
string hashedString = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
return hashedString;
}
my java code returns for bb27aee4 :
46d5acfcd281bca9f1df7c9e38d50576
and my .net code returns:
b767fe33172ec6cbea569810ee6cfc05
I don't know what I have to do...
Please help and thanks in advance.
Its not the problem of MD5 hash generator
MD5 hash for bb27aee4 : 46d5acfcd281bca9f1df7c9e38d50576 &
MD5 hash for BB27AEE4 : b767fe33172ec6cbea569810ee6cfc05
So basically in .NET you are generating MD5 hash for BB27AEE4 instead of bb27aee4
So check for the error in your code
Good Luck
The reason you're seeing different results from your hash is because the encoding used for your string differs. In your .NET code, you specify UTF8 explicitly, while there is no guarantee your Java code does the same; it may very well be using ASCII, which results in different hashes being generated.
If you explicitly specify the same encoding in both your .NET and Java code, you'll end up with the same MD5 hashes as well.

Computing md5 hash

I am computing md5hash of files to check if identical so I wrote the following
private static byte[] GetMD5(string p)
{
FileStream fs = new FileStream(p, FileMode.Open);
HashAlgorithm alg = new HMACMD5();
byte[] hashValue = alg.ComputeHash(fs);
fs.Close();
return hashValue;
}
and to test if for the beginning I called it like
var v1 = GetMD5("C:\\test.mp4");
var v2 = GetMD5("C:\\test.mp4");
and from debugger I listed v1 and v2 values and they are different !! why is that ?
It's because you're using HMACMD5, a keyed hashing algorithm, which combines a key with the input to produce a hash value. When you create an HMACMD5 via it's default constructor, it will use a random key each time, therefore the hashes will always be different.
You need to use MD5:
private static byte[] GetMD5(string p)
{
using(var fs = new FileStream(p, FileMode.Open))
{
using(var alg = new MD5CryptoServiceProvider())
{
return alg.ComputeHash(fs);
}
}
}
I've changed the code to use usings as well.
From the HMACMD5 constructor doc:
HMACMD5 is a type of keyed hash algorithm that is constructed from the
MD5 hash function and used as a Hash-based Message Authentication Code
(HMAC). The HMAC process mixes a secret key with the message data,
hashes the result with the hash function, mixes that hash value with
the secret key again, and then applies the hash function a second
time. The output hash will be 128 bits in length.
With this constructor, a 64-byte, randomly generated key is used.
(Emphasis mine)
With every call to GetMD5(), you're generating a new random key.
You might want to use System.Security.Cryptography.MD5Cng
My guess is that you did something like:
Console.WriteLine(v1);
Console.WriteLine(v2);
or
Console.WriteLine(v1 == v2);
That just shows that the variable values refer to distinct arrays - it doesn't say anything about the values within those arrays.
Instead, try this (to print out the hex):
Console.WriteLine(BitConverter.ToString(v1));
Console.WriteLine(BitConverter.ToString(v2))
Use ToString() methode to get the value of the array byte

C# MD5 Hash results not expected result

I've tried every example I can find on the web but I cannot get my .NET code to produce the same MD5 Hash results from my VB6 app.
The VB6 app produces identical results to this site:
http://www.functions-online.com/md5.html
But I cannot get the same results for the same input in C# (using either the MD5.ComputeHash method or the FormsAuthentication encryption method)
Please help!!!!
As requested, here is some code. This is pulled straight from MSDN:
public string hashString(string input)
{
// Create a new instance of the MD5CryptoServiceProvider object.
MD5 md5Hasher = MD5.Create();
// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
// Return the hexadecimal string.
return sBuilder.ToString();
}
My test string is:
QWERTY123TEST
The results from this code is:
8c31a947080131edeaf847eb7c6fcad5
The result from Test MD5 is:
f6ef5dc04609664c2875895d7da34eb9
Note: The result from the TestMD5 is what I am expecting
Note: I've been really, really stupid, sorry - just realised I had the wrong input. As soon as I hard-coded it, it worked. Thanks for the help
This is a C# MD5 method that i know works, i have used it to authenticate via different web restful APIs
public static string GetMD5Hash(string input)
{
System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] bs = System.Text.Encoding.UTF8.GetBytes(input);
bs = x.ComputeHash(bs);
System.Text.StringBuilder s = new System.Text.StringBuilder();
foreach (byte b in bs)
{
s.Append(b.ToString("x2").ToLower());
}
return s.ToString();
}
What makes the "functions-online" site (http://www.functions-online.com/md5.html) an authority on MD5? For me, it works OK only for ISO-8859-1. But when I try pasting anything other than ISO-8859-1 into it, it returns the same MD5 hash. Try Cyrillic capital B by itself, code point 0x412. Or try Han Chinese symbol for water, code point 0x98A8.
As far as I know, the posted C# applet is correct.

Categories

Resources