问题
On client side I am doing an MD5 encryption of a string and then a BASE 64 encoding on the hash generated.
This final encoded string is then used for comparison on server side.
I was able to do this successfully for many test cases but it failed for the below one.
String for MD5
2679:07071960:09348448:3:08912206:3:EXPRESS:1:EU4NW31E7INEC1X
My MD5 hash string:
291423A531148527A9524EA0924CDF68
My Base64 encoded string:
KRQjpTEUhSepUk6gkkzfaA==
When I try to put the MD5 hash string for BASE64 encoding on http://www.opinionatedgeek.com/dotnet/tools/base64encode/ it generates following string:
MjkxNDIzQTUzMTE0ODUyN0E5NTI0RUEwOTI0Q0RGNjg=
But, when I try to decode my Base64 string, that is "KRQjpTEUhSepUk6gkkzfaA==", here http://www.opinionatedgeek.com/dotnet/tools/Base64Decode/Default.aspx I am getting my Hash Code(opened the .bin file being generated in hex editor).
So, is it possible that a single string may have multiple Base64 encoded value?
I am using the below code for generating the encoded string:
public static String getHashCode(String text)
{
MessageDigest md;
byte[] md5hash = new byte[32];
try{
md = MessageDigest.getInstance("MD5");
md.update(text.getBytes("iso-8859-1"), 0, text.length());
md5hash = md.digest();
}
catch(Exception e)
{
return "-1";
}
String encoded = Base64.encode(md5hash);
String retValue = new String(encoded);
return retValue;
}
Kindly, suggest what is going wrong and how to make sure that we use same digest both on client and server side.
回答1:
You have the MD5 Hash 291423A531148527A9524EA0924CDF68 that generates the Base64 encoded string MjkxNDIzQTUzMTE0ODUyN0E5NTI0RUEwOTI0Q0RGNjg= , which is fine. You have converted the MD5 hash to an ascii hex representation, and base64 encoded that.
However your own getHashCode() works differently, it creates a base64 encoding of the binary representation of your hash code, you have not converted your hash to an ascii hex representation, and that's why you see different base64 encoded strings.
回答2:
The accepted answer solves the problem but does not answer the question.
For example, these base64 values QzNWwq==
and QzNWwr==
encode the same binary value (hex) 433356c2
You can check it at http://kjur.github.io/jsjws/tool_b64udec.html or using the command
echo <<BASE64>> | base64 -d | xxd
In summary
- Two different base 64 encode same value --> true
- Two different values generate the same base64 value --> false (see this)
来源:https://stackoverflow.com/questions/13449595/can-two-different-base-64-encoded-strings-result-into-same-string-if-decoded