I am trying to convert the following C# code to java in order to add it to my new app. The C# code is the short one below and the JAVA is what I managed to pick up but I am sure I did not an identical conversion since the output from the JAVA is not the same as the output from the C#. What changes in teh JAVA are required to make it identical to the C#?
private static string GetMd5Sum(string productIdentifier)
{
var enc = Encoding.Unicode.GetEncoder();
var unicodeText = new byte[productIdentifier.Length * 2];
enc.GetBytes(productIdentifier.ToCharArray(), 0, productIdentifier.Length, unicodeText, 0, true);
MD5 md5 = new MD5CryptoServiceProvider();
var result = md5.ComputeHash(unicodeText);
var sb = new StringBuilder();
for (var i = 0; i < result.Length; i++)
{
sb.Append(result[i].ToString("X2"));
}
return sb.ToString();
}
What I tried is this:
package myTest;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Licensing {
private static String GetMd5Sum(String productIdentifier)
{
byte[] unicodeText = new byte[productIdentifier.length() * 2];
byte[] bt = productIdentifier.getBytes();
int bb=0;
for(int b = 0; b < bt.length; b++ ) {
unicodeText[bb] = bt[b];
bb++;
unicodeText[bb] = 0;
bb++;
}
String s = unicodeText.toString();
byte[] md5Hash = getMd5(s).getBytes();
return bytesToHex(md5Hash);
}
final protected static char[] decimalArray = "0123456789".toCharArray();
public static String bytesToDecimal(byte[] bytes) {
char[] decimalChars = new char[bytes.length * 4];
for ( int j = 0; j < bytes.length; j++ ) {
int v = bytes[j] & 0xFF;
decimalChars[j * 4] = decimalArray[v / 100];
decimalChars[j * 4 + 1] = decimalArray[(v / 10) % 10];
decimalChars[j * 4 + 2] = decimalArray[v % 10];
decimalChars[j * 4 + 3] = ' ';
}
return new String(decimalChars);
}
private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = HEX_ARRAY[v >>> 4];
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
}
return new String(hexChars);
}
private static String getMd5(String input) {
try {
// Static getInstance method is called with hashing MD5
MessageDigest md = MessageDigest.getInstance("MD5");
// digest() method is called to calculate message digest
// of an input digest() return array of byte
byte[] messageDigest = md.digest(input.getBytes());
// Convert byte array into signum representation
BigInteger no = new BigInteger(1, messageDigest);
// Convert message digest into hex value
String hashtext = no.toString(16);
while (hashtext.length() < 32) {
hashtext = "0" + hashtext;
}
return hashtext;
}
// For specifying wrong message digest algorithms
catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
}