HELP!!!
I need some major help here. I need to reproduce the hash algorythm used by our software here at work for use in other projects, but the code currently being used is in Java, and I need to rewrite it in C# such that it will produce the exact same results when provided the same input. Here's the code, can you please help translate this? I've tried but continuously fail.
package de.uplanet.security;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
public final class KeyedSaltedHashing
{
// the algorithm used
private final MessageDigest m_md;
// the message digest
private byte[] m_digest = null;
public KeyedSaltedHashing() throws NoSuchAlgorithmException
{
this("SHA-1");
}
public KeyedSaltedHashing(String p_strAlgorithm) throws NoSuchAlgorithmException
{
m_md = MessageDigest.getInstance(p_strAlgorithm);
m_digest = null;
}
public boolean equals(KeyedSaltedHashing p_another)
{
return Arrays.equals(m_digest, p_another.m_digest);
}
public byte[] makeDigest(byte[] p_arPwd, byte[] p_arSalt, byte[] p_arKey)
throws NullPointerException
{
if (p_arPwd == null || p_arKey == null)
throw new NullPointerException("Cannot handle null parameters.");
m_md.reset();
m_md.update(p_arPwd);
if (p_arSalt != null)
m_md.update(p_arSalt);
return makeDigest(m_md.digest(), p_arKey);
}
public byte[] makeDigest(byte[] p_arHashedPwd, byte[] p_arKey)
throws NullPointerException
{
final byte[] l_ipad;
final byte[] l_opad;
final byte[] l_arTmp;
if (p_arHashedPwd == null || p_arKey == null)
throw new NullPointerException("Cannot handle null parameters.");
m_digest = null;
l_ipad = new byte[64];
l_opad = new byte[64];
Arrays.fill(l_ipad, (byte)0x36);
Arrays.fill(l_opad, (byte)0x5C);
for (int i = 0; i < p_arHashedPwd.length; i++)
{
l_ipad[i] ^= p_arHashedPwd[i];
l_opad[i] ^= p_arHashedPwd[i];
}
m_md.reset();
m_md.update(l_ipad);
m_md.update(p_arKey);
l_arTmp = m_md.digest();
m_md.reset();
m_md.update(l_opad);
m_md.update(l_arTmp);
m_digest = m_md.digest();
return m_digest;
}
public byte[] getDigest()
{
return m_digest;
}
}
take a look at the System.Security.Cryptography namespace
in mscorlib.
Both md5 and sha1, sha256, sha384, and sha512 methods are there.
which c# class you use depends on the algorithm string passed in to your constructor:
KeyedSaltedHashing(String p_strAlgorithm)
From the Java docs this can be either: MD2, MD5, SHA-1, SHA-256, SHA-384, and SHA-512.
So I am not sure if C# supports MD2 natively and it is just named differently or in another namespace or library, google should know though :)
I have never done this translation though, so I can't offer any more advice. But I hope the transition goes as smoothly as possible.
-----------------
Tim Speed
Compilr Developer and CTO