Codename One中的Bouncy Castle库中的MD5方法

huangapple go评论56阅读模式
英文:

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

它们生成相同的输出。这只是网站在显示数据方式上有点晦涩。这是网站的输出:

Codename One中的Bouncy Castle库中的MD5方法

问题在于你只是将字节转换为字符串,但网站只列出了每个字节的十六进制值作为两个字符的字符串。例如,如果你在调试器中停下来检查它,它看起来不同,但如果你将调试器设置为以十六进制显示值(通过右键单击可用),你会看到这个:

Codename One中的Bouncy Castle库中的MD5方法

这是生成相同输出所需的代码。请注意,我强制每个条目使用两个字符:

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:

Codename One中的Bouncy Castle库中的MD5方法

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:

Codename One中的Bouncy Castle库中的MD5方法

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 &amp; 0xff);
    if(val.length() &lt; 2) {
        builder.append(&quot;0&quot;);
    }
    builder.append(val);
}
Log.p(builder.toString());

huangapple
  • 本文由 发表于 2023年3月4日 02:51:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/75630844.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定