How can you generate the same MD5 Hashcode in C# and Java?

前端 未结 4 981
庸人自扰
庸人自扰 2020-12-08 01:29

I have a function that generates a MD5 hash in C# like this:

MD5 md5 = new MD5CryptoServiceProvider();
byte[] result = md5.ComputeHash(data);
StringBuilder s         


        
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-08 02:05

    Hi I m using this code and it works

    C# code :

        public static string ConvertStringToMD5(string ClearText)
    {
    
        byte[] ByteData = Encoding.ASCII.GetBytes(ClearText);
        //MD5 creating MD5 object.
        MD5 oMd5 = MD5.Create();
        //Hash değerini hesaplayalım.
        byte[] HashData = oMd5.ComputeHash(ByteData);
    
        //convert byte array to hex format
        StringBuilder oSb = new StringBuilder();
    
        for (int x = 0; x < HashData.Length; x++)
        {
            //hexadecimal string value
            oSb.Append(HashData[x].ToString("x2"));
        }
    

    and Java code :

        private String getMD5Digest(byte[] buffer) {
        String resultHash = null;
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
    
            byte[] result = new byte[md5.getDigestLength()];
            md5.reset();
            md5.update(buffer);
            result = md5.digest();
    
            StringBuffer buf = new StringBuffer(result.length * 2);
    
            for (int i = 0; i < result.length; i++) {
                int intVal = result[i] & 0xff;
                if (intVal < 0x10) {
                    buf.append("0");
                }
                buf.append(Integer.toHexString(intVal));
            }
    
            resultHash = buf.toString();
        } catch (NoSuchAlgorithmException e) {
        }
        return resultHash;
    }
    

提交回复
热议问题