CryptoServiceProvider hash output does not match online hash generators?

I'm a student and I'm new to programming. This is the first C# program I've tried to write. The program is supposed to read in a text file with clear text and then output a text file with MD5 and SHA-1 hashes. The program works so far as I can tell, however the hashes created by my program do not match the hashes generated by online hash generators. To the best of my knowledge hashes should match if the input word is the same. Is there anything obviously wrong with my code that would cause this?

using System; using System.Text; using System.IO; using System.Security.Cryptography; namespace CreateHash { class Program { const string INPUTFILE = "C:\\ClearTextPasswords.txt"; const string OUTPUTFILEMD5 = "C:\\EncryptedMD5Passwords.txt"; const string OUTPUTFILESHA1 = "C:\\EncryptedSHA1Passwords.txt"; static void Main(string[] args) { string input; int counter = 0; DeleteWriteFile(); StreamReader readFile = new StreamReader(INPUTFILE); while ((input = readFile.ReadLine()) != null) { if(AppendFile(input)) counter++; } readFile.Close(); Console.WriteLine("\nSuccessfully wrote {0} encrypted password(s) to: \n{1} and\n{2} files.\n\nPress any key to exit...", counter.ToString(), OUTPUTFILEMD5, OUTPUTFILESHA1); Console.ReadKey(); } static void DeleteWriteFile() { //Example of try/catch block try { System.IO.File.Delete(OUTPUTFILEMD5); } catch (Exception ex) { Console.WriteLine("There was an error deleting the MD5 Output file: " + ex.Message); } try { System.IO.File.Delete(OUTPUTFILESHA1); } catch (Exception ex) { Console.WriteLine("There was an error deleting the MD5 Output file: " + ex.Message); } } static bool AppendFile(string str) { int x = 0; int y = 0; bool result = false; StreamWriter writeFile1; StreamWriter writeFile2; HashToolkit hashToolkit = new HashToolkit(); //Example of try/catch/finally block try { writeFile1 = new StreamWriter(OUTPUTFILEMD5, true); writeFile1.WriteLine(hashToolkit.GetMd5(str)); writeFile1.Close(); x = 1; } catch (Exception ex) { Console.WriteLine("There was an error writing to the MD5 Output file: " + ex.Message); } finally { writeFile1 = null; } try { writeFile2 = new StreamWriter(OUTPUTFILESHA1, true); writeFile2.WriteLine(hashToolkit.GetSha1(str)); writeFile2.Close(); y = 1; } catch (Exception ex) { Console.WriteLine("There was an error writing to the SHA1 Output file: " + ex.Message); } finally { writeFile2 = null; } if (x * y != 0) result = true; return result; } } public class HashToolkit { public HashToolkit() { } public string GetMd5(string str) { MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); string input = string.Empty; byte[] hashedData = md5.ComputeHash(Encoding.Unicode.GetBytes(str)); foreach (byte b in hashedData) { input += String.Format("{0,2:X2}", b); } return input; } public string GetSha1(string str) { SHA1 sha = new SHA1CryptoServiceProvider(); string input = string.Empty; byte[] hashedData = sha.ComputeHash(Encoding.Unicode.GetBytes(str)); foreach (byte b in hashedData) { input += String.Format("{0,2:X2}", b); } return input; } } }

Any help would be much appreciated. Thank you for your time.


That's because you can't hash strings, you can only hash bytes. For that reason you need to convert to bytes first. And you are using UTF16 for that. The online tool probably uses UTF8 or some ASCII-style encoding. Find out which it uses and use it too.

Category:c# Time:2012-10-28 Views:0
Tags: .net

Related post

  • Using grep to match md5 hashes 2010-12-22

    How can I match md5 hashes with the grep command? In php I used this regular expression pattern in the past: /^[0-9a-f]{32}$/i But I tried: grep '/^[0-9a-f]{32}$/i' filename grep '[0-9a-f]{32}$/' filename grep '[0-9a-f]{32}' filename And other varian

  • Java MD5 Hash Not Matching .NET Hash 2011-03-23

    I have a webservice that is written in C# handling some validation of values. In it I need to check a MD5 hash generated in the calling Java client. The Java client generates the hash in this manner Charset utf8Charset = Charset.forName("UTF-8"); byt

  • InCorrect output using Rfc2898DeriveBytes for password hashing 2011-11-15

    I am certainly sure i am doing something wrong here. Using .net implementation of the algorithm i hash the password to store in database along with the salt used to hash. On validating the same password with the existing hash does not match.Here is m

  • Fuzzy match two hash tables? 2010-05-10

    I'm looking for ideas on how to best match two hash tables containing string key/value pairs. Here's the actual problem I'm facing: I have structured data coming in which is imported into the database. I need to UPDATE records which are already in th

  • Checking for string matches using hashes, without double-checking the entire string 2010-11-08

    I'm trying to check if two strings are identical as quickly as possible. Can I protect myself from hash collisions without also comparing the entire string? I've got a cache of items that are keyed by a string. I store the hash of the string, the len

  • Password does not match with hash algorithm (SQL Server) 2011-02-05

    I got a problem with SQL Server. My Task is it to realize a simple SQL Serverbased usersystem with PHP. The databases are also used by a MMORPG so I am not allowed to change the database structure or hashing alogrithms. The real cause of my problem i

  • HMC SHA1 hash - C# producing different hash output than Ruby 2011-08-24

    I'm trying to quickly get a buggy .Net client library for a third party service I'm using to work. The original library (which works) is written in Ruby, but their equivalent library for DotNet produces differing hash output to the Ruby library. The

  • In RequireJs, how do I instruct the optimizer to to produce hash output files names? 2011-09-05

    I run the optimizer like this sudo /usr/local/bin/node /tmp/r.j/r.js -o name=main out=test.js baseUrl=. for test Now, how do I tell the optimizer to output the filename as a hash of the content (obviously to set max expires) and then rename the depen

  • How weak are 64 bit hashs? Can I generate a hash of length X? 2011-03-10

    I am working on an application where I need to hash binary data, and store the hash in a structure 64 bits long. I am looking for a cryptographic hash function. Ripemd-64 and elf-64 are some possibilities that I have found, but I can't find much data

  • Hashes generated by Rabin Karp Rolling Hash not reflecting on the Text 2012-01-15

    Note: Lots of Possible duplicates, but nothing seems to be solving my problem. I am working on a Plagiarism detection based on MOSS. After successfully implementing a filter which strips out all the necessary details(comments,punctuations etc) I hash

  • Perl: Define hash with reference to the same hash, $this->{key}? 2010-01-27

    How would I create a hash like the follow: my %hash = (key1=>"Something", key2=>$hash{key1} . "Else"); Can this not be done while when I declare the hash? So far, the only thing I came up with was: my %hash = (key1=>"Something"); $hash{key2}

  • Can I convert an ASCII MD5 hashed password into a Unicode MD5 hashed password? 2010-04-25

    I'm looking for help to convert an ASCII MD5 hashed password into a Unicode MD5 hashed password? For example, I'll use the string "password" . When it's converted to an ascii byte array, I get a base64 encoded hash of X03MO1qnZdYdgyfeuILPmQ== When it

  • sum array of hashes based on other fields in hash 2010-12-06

    I have an array of hashes that looks like this: [{:head_count=>150.5, :group=>"NW", :estimated_ship_date=>"201105", :yard=>"wcc"}, {:head_count=>201.0, :group=>"NW", :estimated_ship_date=>"201105", :yard=>"wcc"}, {:head_count=

  • Recommended hash function for overwriting NSObject's hash method 2011-05-06

    What's a good hash function for overwriting NSObject's hash method in your custom classes? --------------Solutions------------- Here is a good community wiki page discussing overwriting the functions Implementing -hash / -isEqual: / -isEqualTo...: fo

  • How to check if an hash is "completely" included in another hash? 2011-09-28

    I am using Ruby on Rails 3.1.0 and I would like to check if an hash is "completely" included in another hash and return a boolean value. Say I have those hashes: hash1 = { :key1 => 'value1', :key2 => 'value2', :key3 => 'value3' } hash2 = { :

  • Hashing function of any live object (hash table)? 2011-09-30

    Not sure whether it is sensible reopen my earlier thread on Hashing URL. Nonetheless, I am still curious know how this work undercover. Assumption: We have a hashtable with n (where n < Infinity) element where asymptotic time complexity is o(1); w

  • Hashing a string for use in hash table (Double Hashing) 2011-11-09

    I am trying to use Double Hashing to hash a String key into a hash table. I did something like: protected int getIndex(String key) { int itr = 0, size = this.values.length, index1, index2, index = 0; do { // do double hashing to get index for curr [i

  • In a hash tree, are non-leaf nodes direct hashes of data, or are they hashes of sub-hashes? 2011-12-07

    I am looking on the wikipedia article for hash trees, and I am slightly confused by their diagram. A leaf node obviously contains the hash of the underlying data. Are leaf nodes in hash trees different than any non-leaf node? Do non-leaf nodes contai

  • How to use awk to search for a complete match of text within one column of a CSV file and to only output the first matching line? 2012-04-18

    I am using the answer from How to restrict grep to search only the one column within a CSV file, but to output matching lines in their entirety? to search particular columns with awk, then output matching rows, e.g.: awk [email protected] "{if (\$2 ~ /$find_me/ )

Copyright (C), All Rights Reserved.

processed in 0.994 (s). 13 q(s)