get same hash string from .NET and java?

G

G Tsang

Hello All,

Is it possible to get the same hashed string on .NET and Java using the
same hashing algorithm (e.g. MD5, SHA)??

On .NET side, the token is generated using the following code:
Private Function HashEncrypt(ByVal strInput as String) As String
Dim bytHash as Byte()
Dim uEncode As New System.Text.UnicodeEncoding
' - - - STORE THE SOURCE STRING INTO A BYTE ARRAY - - -
Dim bytSource() As Byte = uEncode.GetBytes(strInput)
Dim SHA1 As New System.Security.Cryptography.SHA1CryptoServiceProvider
' - - - CREATE THE HASH - - -
bytHash = SHA1.ComputeHash(bytSource)
' - - - RETURN AS A BASE64 ENCODED STRING - - -
Return Convert.ToBase64String(bytHash)
End Function


On the java side, the token is generated as follow:

MessageDigest _digester = null;
_digester = MessageDigest.getInstance("SHA1");
_digester.reset();
byte[] utf8 = _msg.getBytes("UTF-8");
_digester.update(utf8);
byte[] _tokenBytes = _digester.digest();
String s = new sun.misc.BASE64Encoder().encode(_tokenBytes);

Thanks for your help!

Grace

*** Sent via Devdex http://www.devdex.com ***
Don't just participate in USENET...get rewarded for it!
 
J

Jon Skeet [C# MVP]

G Tsang said:
Is it possible to get the same hashed string on .NET and Java using the
same hashing algorithm (e.g. MD5, SHA)??

If you use the same hashing algorithm and give it the same data, you
should indeed get the same hash.
On .NET side, the token is generated using the following code:
Private Function HashEncrypt(ByVal strInput as String) As String
Dim bytHash as Byte()
Dim uEncode As New System.Text.UnicodeEncoding
' - - - STORE THE SOURCE STRING INTO A BYTE ARRAY - - -
Dim bytSource() As Byte = uEncode.GetBytes(strInput)

So this is converting the string in Unicode encoding...
Dim SHA1 As New System.Security.Cryptography.SHA1CryptoServiceProvider
' - - - CREATE THE HASH - - -
bytHash = SHA1.ComputeHash(bytSource)
' - - - RETURN AS A BASE64 ENCODED STRING - - -
Return Convert.ToBase64String(bytHash)
End Function


On the java side, the token is generated as follow:

MessageDigest _digester = null;
_digester = MessageDigest.getInstance("SHA1");
_digester.reset();
byte[] utf8 = _msg.getBytes("UTF-8");

.... and this is using UTF-8. So you're not giving it the same data.
That's the problem.
_digester.update(utf8);
byte[] _tokenBytes = _digester.digest();
String s = new sun.misc.BASE64Encoder().encode(_tokenBytes);

Don't use sun.* packages - see the Java documentation for more details.
 
Top