Skip to content
Advertisement

VB to java problems

I have VB code and want to convert it to Java for a mobile app, but I always get a different end result in Java and I don’t know where my mistake is, or what I’m doing wrong.

VB Code:

Private Function PasswortlevelHash(ByVal Passworltevel As String, ByVal 

    Tag As String, ByVal Monat As String, ByVal Jahr As String) As String
    Dim uEncode As New UnicodeEncoding
    Dim md5 As New MD5CryptoServiceProvider
    
    Dim strForHash As String = "MS-U4_2022_10_10setup"
    Dim bytHashNeu() As Byte = uEncode.GetBytes(strForHash)
    Dim strHash1 As String = Convert.ToBase64String(md5.ComputeHash(bytHashNeu))
    PasswortlevelHash = strHash1

End Function

Result: h1qKTNN456AqTZUPPaft3Q==

Java:

private String PasswortlevelHash(String strPasswortlevel, String strDay, String strMonth, String strYear) throws Exception {

    MD5 md5 = new MD5();
    
    String strForHash = "MS-U4_2022_10_10setup"
    byte[] bytHash = strForHash.getBytes("UTF-8");
    byte[] bytBOM = {(byte) 0xEF, (byte) 0xBB, (byte) 0xBF };
    byte[] bytGesamt =  addAll(bytBOM, bytHash);
    
    String strHash = getMD5(bytGesamt);
    String strHash2 = Base64.getEncoder().encodeToString(strHash.getBytes("UTF-8"));
    
    return strHash2 ;
}

Result: NDM5MjFmZjJiMjc1YjRlZTI0YmQ4NGI0YTQ2ZjQxMTI=

Advertisement

Answer

The .NET UnicodeEncoding class handles UTF-16:

Represents a UTF-16 encoding of Unicode characters.

But you used UTF-8 in the Java code.

UPDATE

As Mark pointed out, you also have an extra hex conversion. Here is a working Java code:

import java.io.UnsupportedEncodingException;
import java.security.*;
import java.util.Base64;

public class Test
{
    public static String getHash(String s) throws NoSuchAlgorithmException, UnsupportedEncodingException
    {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] md5 = md.digest(s.getBytes("UTF-16LE"));
        return Base64.getEncoder().encodeToString(md5);
    }

    public static void main(String args[]) throws NoSuchAlgorithmException, UnsupportedEncodingException
    {
        System.out.println(getHash("MS-U4_2022_10_10setup"));
    }
}

Output:

h1qKTNN456AwTZUPPaft3Q==
Advertisement