简体   繁体   English

C ++与Java中的md5 base64编码器

[英]md5 base64 encoder in C++ vs Java

I have a cross-language problem regarding md5 :). 我有关于md5 :)的跨语言问题。 I have this code in Java: 我在Java中有这个代码:

BASE64Encoder encoder = new BASE64Encoder();
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(someString.getBytes());
byte[] bMac = md.digest();
String anotherString = encoder.encodeBuffer(bMac);

This encodes and hashes a string in md5 and base64. 这会在md5和base64中对字符串进行编码和哈希处理。 A string like "aaa&1" becomes Fv4eRn4R0/mB+uc4j1GGaA== 像“aaa&1”这样的字符串变为Fv4eRn4R0 / mB + uc4j1GGaA ==

Now the problem is: how to do this in C++? 现在问题是:如何在C ++中执行此操作? I'm using openssl/md5.h, but like any other online md5 encoder (after a small google search), it gets a hash like: 16fe1e467e11d3f981fae7388f518668 我正在使用openssl / md5.h,但与任何其他在线md5编码器一样(在谷歌搜索之后),它会得到如下的哈希:16fe1e467e11d3f981fae7388f518668

Which is in hex it seems. 似乎是十六进制。 If I try to transform the md5 hash in base64, I get a completely different hash (longer and uglier :) ). 如果我尝试在base64中转换md5哈希,我会得到一个完全不同的哈希(更长和更丑):)。

Help!!! 救命!!!

Thank you! 谢谢!

LE: I use the MD5 method from openssl/md5.h, as AZI pointed out. LE:我使用openssl / md5.h中的MD5方法,正如AZI指出的那样。

Here is the C++ code to obtain md5 这是获取md5的C ++代码

#include <openssl/md5.h>
unsigned char *MD5(const unsigned char *d, 
               unsigned long n,
               unsigned char *md);

example: 例:

unsigned char inbuf[] = "aaa&1";
unsigned char outbuf[20];
MD5(inbuf, strlen(inbuf), outbuf);

for (i = 0; i < 20; i++) {
    printf("%02x ", outbuf[i]);
}

if Hex of 16fe1e467e11d3f981fae7388f518668 converted to Base64 then Hex to Base64 you will get Fv4eRn4R0/mB+uc4j1GGaA== 如果16fe1e467e11d3f981fae7388f518668十六进制转换为Base64然后Hex转换为Base64 您将得到Fv4eRn4R0/mB+uc4j1GGaA==

May refer to Howto base64 encode with C/C++ and OpenSSL to encode this to Base64 可以参考使用C / C ++和OpenSSL的Howto base64编码将其编码为Base64

The solution is to use everything Azi and Mike Seymour said... So, to obtain the MD5 hash, you have to use the solution presented by Azi. 解决方案是使用Azi和Mike Seymour所说的一切......所以,要获得MD5哈希,你必须使用Azi提供的解决方案。 Then the thing in Java uses something like Mike suggested... it encodes in base64 from binary. 然后Java中的东西使用像Mike建议的东西......它从二进制编码在base64中。

My solution was to look at the code from the link provided by Azi: 我的解决方案是查看Azi提供的链接中的代码:

http://tomeko.net/online_tools/hex_to_base64.php?lang=en http://tomeko.net/online_tools/hex_to_base64.php?lang=en

And to port it into C++. 并将其移植到C ++中。 Fortunately it wasn't that hard to do... If anyone wants the C++ code, leave a comment. 幸运的是,这并不难:如果有人想要C ++代码,请发表评论。 Thank you all! 谢谢你们!

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

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