473,836 Members | 1,832 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

HELP -- ASCIIEncoding Problem

Hi,

I am using a function to hash a string value:

public string generateMD5Hash (string input)
{
MD5 md5Provider; // MD5 provider instance

// generate byte code for input
byte[] inputData = ASCIIEncoding.A SCII.GetBytes(i nput);

// compute MD5 hash
md5Provider = new MD5CryptoServic eProvider();
byte[] hashResult = md5Provider.Com puteHash(inputD ata);

return ASCIIEncoding.A SCII.GetString( hashResult);
}

The last return statement (ASCIIEncoding. ..) returns different values
if used in .NET Framework 1.1 (or 1.0) and .NET Framework 2.0. That
means that my .NET Framework 2.0 version of application (written in
C#) will not execute sam as writen in .NET Framework 1.1.

Did something changed? How to fix this?

any help will be appreciated,
_dino_
Dec 30 '05 #1
4 6402
Dino Buljubasic <di**@noplaceli kehome.com> wrote:
I am using a function to hash a string value:

public string generateMD5Hash (string input)
{
MD5 md5Provider; // MD5 provider instance

// generate byte code for input
byte[] inputData = ASCIIEncoding.A SCII.GetBytes(i nput);

// compute MD5 hash
md5Provider = new MD5CryptoServic eProvider();
byte[] hashResult = md5Provider.Com puteHash(inputD ata);

return ASCIIEncoding.A SCII.GetString( hashResult);
}

The last return statement (ASCIIEncoding. ..) returns different values
if used in .NET Framework 1.1 (or 1.0) and .NET Framework 2.0. That
means that my .NET Framework 2.0 version of application (written in
C#) will not execute sam as writen in .NET Framework 1.1.

Did something changed? How to fix this?


I suspect it is only returning a different value when the byte is
greater than 127. To be honest, I think that's reasonable, as the
behaviour isn't well-defined in that situation, as ASCII doesn't
contain any values greater than 127.

For those interested, here's a sample which demonstrates the "problem":

using System;
using System.Text;

public class Test
{
static void Main()
{
string x = Encoding.ASCII. GetString (new byte[]{128});

Console.WriteLi ne ((int)x[0]);
}
}

Now, as to how you should fix it:
1) Encode the input string with UTF-8 instead of ASCII. That means you
won't lose data when the input contains non-ASCII characters. (In this
case as you're just taking an MD5 hash, it just means your hash is
weaker than it should be. However, it's a good idea to try not to use
an ASCII encoding when the data might contain non-ASCII characters on
principle.

2) Encode the resulting binary data using Base64 -
Convert.ToBase6 4String is the easiest method here.

Here's the changed method:

public string generateMD5Hash (string input)
{
// generate byte code for input
byte[] inputData = Encoding.UTF8.G etBytes(input);

// compute MD5 hash
MD5 md5Provider = new MD5CryptoServic eProvider();
byte[] hashResult = md5Provider.Com puteHash(inputD ata);

return Convert.ToBase6 4String(hashRes ult);
}
Now, if you've got old values which need to be matched, you'll have to
mimic the old behaviour instead, which is slightly trickier. I won't do
that now, because you might not need it - let me know if you do, and
I'll see what I can do.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Dec 30 '05 #2
Hi,

Thank you for your reply. I haven't had time to look at your example
but you are right, it was returning different values. I did some
research on internet and found a post from a guy whose name I
unfortunatelly don't remember anymore (my appologies). Anyways, hHere
is how I solved it:

public string generateMD5Hash (string input)
{
MD5 md5Provider; // MD5 provider instance

// generate byte code for input
byte[] inputData = ASCIIEncoding.A SCII.GetBytes(i nput);

// compute MD5 hash
md5Provider = new MD5CryptoServic eProvider();
byte[] hashResult = md5Provider.Com puteHash(inputD ata);
byte[] fixedByteArray = new byte[hashResult.Leng th];
for (int i = 0; i < fixedByteArray. Length; i++)
{
fixedByteArray[i] = (byte)((int)has hResult[i] & 127);
}
string hashedPassword =
ASCIIEncoding.A SCII.GetString( fixedByteArray) ;
//return ASCIIEncoding.A SCII.GetString( hashResult);
return hashedPassword;
}

It seam to be working right. Let me know if you have any suggestions
please.

I appreciate your help,
_dino_

On Fri, 30 Dec 2005 18:31:08 -0000, Jon Skeet [C# MVP]
<sk***@pobox.co m> wrote:
Dino Buljubasic <di**@noplaceli kehome.com> wrote:
I am using a function to hash a string value:

public string generateMD5Hash (string input)
{
MD5 md5Provider; // MD5 provider instance

// generate byte code for input
byte[] inputData = ASCIIEncoding.A SCII.GetBytes(i nput);

// compute MD5 hash
md5Provider = new MD5CryptoServic eProvider();
byte[] hashResult = md5Provider.Com puteHash(inputD ata);

return ASCIIEncoding.A SCII.GetString( hashResult);
}

The last return statement (ASCIIEncoding. ..) returns different values
if used in .NET Framework 1.1 (or 1.0) and .NET Framework 2.0. That
means that my .NET Framework 2.0 version of application (written in
C#) will not execute sam as writen in .NET Framework 1.1.

Did something changed? How to fix this?


I suspect it is only returning a different value when the byte is
greater than 127. To be honest, I think that's reasonable, as the
behaviour isn't well-defined in that situation, as ASCII doesn't
contain any values greater than 127.

For those interested, here's a sample which demonstrates the "problem":

using System;
using System.Text;

public class Test
{
static void Main()
{
string x = Encoding.ASCII. GetString (new byte[]{128});

Console.WriteLi ne ((int)x[0]);
}
}

Now, as to how you should fix it:
1) Encode the input string with UTF-8 instead of ASCII. That means you
won't lose data when the input contains non-ASCII characters. (In this
case as you're just taking an MD5 hash, it just means your hash is
weaker than it should be. However, it's a good idea to try not to use
an ASCII encoding when the data might contain non-ASCII characters on
principle.

2) Encode the resulting binary data using Base64 -
Convert.ToBase 64String is the easiest method here.

Here's the changed method:

public string generateMD5Hash (string input)
{
// generate byte code for input
byte[] inputData = Encoding.UTF8.G etBytes(input);

// compute MD5 hash
MD5 md5Provider = new MD5CryptoServic eProvider();
byte[] hashResult = md5Provider.Com puteHash(inputD ata);

return Convert.ToBase6 4String(hashRes ult);
}
Now, if you've got old values which need to be matched, you'll have to
mimic the old behaviour instead, which is slightly trickier. I won't do
that now, because you might not need it - let me know if you do, and
I'll see what I can do.


Dec 30 '05 #3
Dino Buljubasic <di**@noplaceli kehome.com> wrote:
Thank you for your reply. I haven't had time to look at your example
but you are right, it was returning different values. I did some
research on internet and found a post from a guy whose name I
unfortunatelly don't remember anymore (my appologies). Anyways, hHere
is how I solved it:

public string generateMD5Hash (string input)
{
MD5 md5Provider; // MD5 provider instance

// generate byte code for input
byte[] inputData = ASCIIEncoding.A SCII.GetBytes(i nput);

// compute MD5 hash
md5Provider = new MD5CryptoServic eProvider();
byte[] hashResult = md5Provider.Com puteHash(inputD ata);
byte[] fixedByteArray = new byte[hashResult.Leng th];
for (int i = 0; i < fixedByteArray. Length; i++)
{
fixedByteArray[i] = (byte)((int)has hResult[i] & 127);
}
string hashedPassword =
ASCIIEncoding.A SCII.GetString( fixedByteArray) ;
//return ASCIIEncoding.A SCII.GetString( hashResult);
return hashedPassword;
}

It seam to be working right. Let me know if you have any suggestions
please.


Do you know that input will always be ASCII? If not, you may still get
different results if ASCIIEncoding has changed behaviour in terms of
GetBytes as well as GetString.

Also, you don't need to create a new byte array - you can just do:

for (int i = 0; i < hashResult.Leng th; i++)
{
hashResult[i] = (byte)(hashResu lt[i] & 127);
}

This is what's needed for backwards compatibility with the previous
behaviour - if you ever get a chance to change to the code I suggested,
it would be a more sensible long-term solution IMO.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Dec 31 '05 #4
Thank you Jon, ... yes my input will always be ascii.

I will try to get back to it today and change it.

I appreciate your help
_dino_

On Sat, 31 Dec 2005 07:58:08 -0000, Jon Skeet [C# MVP]
<sk***@pobox.co m> wrote:
Dino Buljubasic <di**@noplaceli kehome.com> wrote:
Thank you for your reply. I haven't had time to look at your example
but you are right, it was returning different values. I did some
research on internet and found a post from a guy whose name I
unfortunatelly don't remember anymore (my appologies). Anyways, hHere
is how I solved it:

public string generateMD5Hash (string input)
{
MD5 md5Provider; // MD5 provider instance

// generate byte code for input
byte[] inputData = ASCIIEncoding.A SCII.GetBytes(i nput);

// compute MD5 hash
md5Provider = new MD5CryptoServic eProvider();
byte[] hashResult = md5Provider.Com puteHash(inputD ata);
byte[] fixedByteArray = new byte[hashResult.Leng th];
for (int i = 0; i < fixedByteArray. Length; i++)
{
fixedByteArray[i] = (byte)((int)has hResult[i] & 127);
}
string hashedPassword =
ASCIIEncoding.A SCII.GetString( fixedByteArray) ;
//return ASCIIEncoding.A SCII.GetString( hashResult);
return hashedPassword;
}

It seam to be working right. Let me know if you have any suggestions
please.


Do you know that input will always be ASCII? If not, you may still get
different results if ASCIIEncoding has changed behaviour in terms of
GetBytes as well as GetString.

Also, you don't need to create a new byte array - you can just do:

for (int i = 0; i < hashResult.Leng th; i++)
{
hashResult[i] = (byte)(hashResu lt[i] & 127);
}

This is what's needed for backwards compatibility with the previous
behaviour - if you ever get a chance to change to the code I suggested,
it would be a more sensible long-term solution IMO.


Jan 4 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
7367
by: mt404 | last post by:
Hi, I was wondering if someone might be able to provide some guidance on how I could make an http request from a C# library. Basically I have a library which accepts a couple of arguments that I use to construct a dynamic http URL address. I wan't to then make a call to this address, capture the data stream it returns, and return that to the application which called the library. I know how to do most everything but I'm not sure how...
4
12818
by: Michael H | last post by:
I need to pass my XML string as a stream to a method; eg. public SubmitResult ClickToRecord.Submit( Stream stream, ConflictResolutionPolicy policy, out ProgramDetails programsInConflict )
3
1871
by: red | last post by:
I have this: using System; using System.Runtime.InteropServices; using System.Text; class FileReader { const uint GENERIC_READ = 0x80000000; const uint OPEN_EXISTING = 3;
1
1282
by: intrader | last post by:
I have a .NET interop assembly Hash.MD5Sum with two methods Identity and GetMD5Sum. I want to call the methods from ASP (JScript), The debugger tells me that object oMD5Sum has one the ToString() method. How do I get the Identity and GetMD5Sum methods to be accessible? I include the entire .net assembley followed by a snippet of the ASP code. /////The code of the .NET assembly is: using System;
2
1870
by: intrader | last post by:
I have a .NET interop assembly Hash.MD5Sum with two methods Identity and GetMD5Sum. I want to call the methods from ASP (JScript), The debugger tells me that object oMD5Sum has only one method (ToString()). How do I get the Identity and GetMD5Sum methods to be accessible? I include the entire .net assembley followed by a snippet of the ASP code. /////The code of the .NET assembly is: using System;
6
2544
by: momo | last post by:
Guys I need your help on this. I have this one problem and I admitted I am a novice at this. This is a Code Behind in an aspx page. You will see where I have the plus signs below in SecureQueryString2.vb where I am calling another Class called "InvalidQueryStringException". My problem is where do I put this code so it can be called from SecureQueryString2.vb. I have tried to put it in the same code behind SecureQueryString2.vb and I get...
0
1315
by: jdp | last post by:
I'm converting an asp.net 1.1 app to 2.0 and am having difficulty determining why ASCIIEncoding.GetString returns a different value in ..NET 2.0 than 1.1. The code is simple but I can't locate the problem. If someone could point out my oversight, I'd greatly appreciate it. Thanks in advance! Dim md5Hasher As New MD5CryptoServiceProvider Dim encoder As New ASCIIEncoding Dim strHashedBytes As Byte() =
6
3366
by: AppleBag | last post by:
I'm having the worst time trying to login to myspace through code. Can someone tell me how to do this? Please try it yourself before replying, only because I have asked this a couple of times in the past in other places, and while the help was much appreciated, it seemed everyone just wanted to 'theoretically' explain how to do it, but when I tried to do it myself, I couldn't login. I want to simply pass the email address and password to...
5
3202
by: mcfly1204 | last post by:
I am attempting to use WebRequest to access a page that requires a login/password to access. My last WebRequest continues to timeout. Any help or thoughts would be appreciated. namespace FormsAuthTest { class Program { static void Main(string args) { HttpWebRequest request = null;
0
9810
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9654
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10818
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10526
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9348
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7770
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6972
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5809
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3094
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.