英文:
Codename One MD5 method in Bouncy Castle Library
问题
以下是您要翻译的内容:
"Referencing this older question, I am trying to generate a MD5 hash, but I am getting a result that is not similar to an outcome that this MD5 web generator gives.
Here is the code I am trying
String data = "XXXXXXXXXXXXX";
MD5Digest md5Digest = new MD5Digest();
try {
byte[] b = data.getBytes("UTF-8");
md5Digest.update(b, 0, b.length);
byte[] hash = a byte[md5Digest.getDigestSize()];
md5Digest.doFinal(hash, 0);
signature = a String(hash, "UTF-8");
} catch (Exception ex) {
Log.e(ex);
}
What is wrong?"
英文:
Referencing this older question, I am trying to generate a MD5 hash, but I am getting a result that is not similar to an outcome that this MD5 web generator gives.
Here is the code I am trying
String data = "XXXXXXXXXXXXX";
MD5Digest md5Digest = new MD5Digest();
try {
byte[] b = data.getBytes("UTF-8");
md5Digest.update(b, 0, b.length);
byte[] hash = new byte[md5Digest.getDigestSize()];
md5Digest.doFinal(hash, 0);
signature = new String(hash, "UTF-8");
} catch (Exception ex) {
Log.e(ex);
}
What is wrong?
答案1
得分: 0
它们生成相同的输出。这只是网站在显示数据方式上有点晦涩。这是网站的输出:
问题在于你只是将字节转换为字符串,但网站只列出了每个字节的十六进制值作为两个字符的字符串。例如,如果你在调试器中停下来检查它,它看起来不同,但如果你将调试器设置为以十六进制显示值(通过右键单击可用),你会看到这个:
这是生成相同输出所需的代码。请注意,我强制每个条目使用两个字符:
StringBuilder builder = new StringBuilder();
for(byte current : hash) {
String val = Integer.toHexString(current & 0xff);
if(val.length() < 2) {
builder.append("0");
}
builder.append(val);
}
Log.p(builder.toString());
英文:
They do produce the same output. It's just the website being obtuse about how the data is displayed. This is the output of the website:
The problem is that you just take the bytes and convert them to a String as is. But the website just lists the hexdecimal value of each byte as a two character string. E.g. if you stop in the debugger on the value and inspect it then it looks different but if you set the debugger to show the value as hexdecimal (available via the right click) then you see this:
This is the code you would need to produce the same output. Notice that I force two characters for every entry:
StringBuilder builder = new StringBuilder();
for(byte current : hash) {
String val = Integer.toHexString(current & 0xff);
if(val.length() < 2) {
builder.append("0");
}
builder.append(val);
}
Log.p(builder.toString());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论