简体   繁体   English

等效于MD5CryptoServiceProvider的Java算术哈希和ToBase64String

[英]Java equivalent to MD5CryptoServiceProvider computeHash & ToBase64String

I compute MD5 hash for a string in C# the following way: 我通过以下方式在C#中为字符串计算MD5哈希值:

var provider = new System.Security.Cryptography.MD5CryptoServiceProvider();
var bytes= Encoding.Unicode.GetBytes(value);
bytes = provider.ComputeHash(bytes);
return Convert.ToBase64String(bytes);

I need to do the same calculation in Java (Android) to match the hash produced using the above method. 我需要在Java(Android)中进行相同的计算,以匹配使用上述方法生成的哈希。 I tried the following with no luck: 我没有运气就尝试了以下方法:

1. 1。

byte[] encoded = Base64.encodeBase64(str.getBytes());
return new String(encoded);

2. 2。

String digest = null;

MessageDigest md = MessageDigest.getInstance("MD5");
byte[] hash = md.digest(message.getBytes("UTF-8"));

//converting byte array to Hexadecimal String
StringBuilder sb = new StringBuilder(2*hash.length);
for(byte b : hash){
    sb.append(String.format("%02x", b&0xff));
}

digest = sb.toString();

3. 3。

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;

EDIT: 编辑:

The Objective C method that produced the C# matching values is this: 产生C#匹配值的Objective C方法是这样的:

NSMutableString *encodedData = [NSMutableString string];

int i = 0, j = 0;

unsigned char char_array_3[3];

unsigned char char_array_4[5];



memset(char_array_3, 0, 3*sizeof(char));

memset(char_array_4, 0, 5*sizeof(char));



int length = [md5Data length];

char *bytes = (char*)[md5Data bytes];



while(length--) {

    char_array_3[i++] = *(bytes++);

    if (i == 3) {

        char_array_4[0] = kBase64Alphabet[(char_array_3[0] & 0xfc)>>2];

        char_array_4[1] = kBase64Alphabet[((char_array_3[0] &

                                            0x03) <<4) + ((char_array_3[1] & 0xf0) >>4)];

        char_array_4[2] = kBase64Alphabet[((char_array_3[1] &

                                            0x0f) <<2) + ((char_array_3[2] & 0xc0) >>6)];

        char_array_4[3] = kBase64Alphabet[char_array_3[2]&0x3f];



        [encodedData appendString:[NSString

                                   stringWithUTF8String:(const char*)char_array_4]];



        i = 0;

    }

}



if (i) {

    for(j=i; j<3; j++)

        char_array_3[j] = '\0';



    char_array_4[0] = kBase64Alphabet[(char_array_3[0] & 0xfc)>>2];

    char_array_4[1] = kBase64Alphabet[((char_array_3[0] & 0x03)

                                       <<4) + ((char_array_3[1] & 0xf0) >>4)];

    char_array_4[2] = kBase64Alphabet[((char_array_3[1] & 0x0f)

                                       <<2) + ((char_array_3[2] & 0xc0) >>6)];

    char_array_4[3] = kBase64Alphabet[char_array_3[2]&0x3f];



    char_array_4[i+1] = 0;

    [encodedData appendString:[NSString

                               stringWithUTF8String:(const char*)char_array_4]];



    while((i++<3))

        [encodedData appendString:[NSString stringWithUTF8String:"="]];

    }



    return encodedData;

}

Example

 `wattlebird` in C# -> `ixfbWnWq9QmLecMFCzaZcw==`
 `wattlebird` in java -> `GTd5lE58tKIlpdmppEVurw==`

Base64 != Hex . Base64 != 十六进制 You can use Base64 from apache commons-codec , 您可以从apache commons-codec使用Base64

import org.apache.commons.codec.binary.Base64;

// ...

public static String hashValue(String value) {
    String digest = null;
    try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] hash = md.digest(value.getBytes("UTF-16LE")); // <-- note encoding
        return new String(Base64.encodeBase64(hash));
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return null;
}

Base64 is not just the values of the bytes in hex. Base64不仅仅是十六进制的字节值。 (here is the RFC spec for how to encode in Base64 RFC 4648 ) (这是有关如何在Base64 RFC 4648中进行编码的RFC规范)

Android has a build in class to work with Base64 encoding android.util.Base64 Android有一个内置类可与Base64编码android.util.Base64

MessageDigest md = MessageDigest.getInstance("MD5");
byte[] hash = md.digest(message.getBytes("UTF-8"));

String base64 = Base64.encodeToString(hash, Base64.DEFAULT);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM