13,100
社区成员
发帖
与我相关
我的任务
分享
byte[] keys = {(byte) 0x69, (byte) 0x70, (byte) 0x68, (byte) 0x6F, (byte) 0x6E, (byte) 0x65, (byte) 0x00, (byte) 0x00, (byte) 0x33, (byte) 0x30, (byte) 0x35, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x00, (byte) 0x69, (byte) 0x70, (byte) 0x68, (byte) 0x6F, (byte) 0x6E, (byte) 0x65, (byte) 0x00, (byte) 0x00};
,我要对该数组进行MD5加密,我现在写了一个方法但加密后的结果不对。 其返回结果应该是“fa692fe3210f01856*******42df”才对,大家帮我想想算法,或实现啊!!!!?纠结,最好是提供源码。。。 private static char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', 'a', 'b', 'c', 'd', 'e', 'f'};
/**
* MD5加密
* 对一段String生成MD5加密信息
* @param source
* @return 生成的MD5信息
*/
public final String getMD5(byte[] source) {
String s = null;
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(source);
byte tmp[] = md.digest(); // MD5 的计算结果是一个 128 位的长整数,
// 用字节表示就是 16 个字节
char str[] = new char[16 * 2]; // 每个字节用 16 进制表示的话,使用两个字符,
// 所以表示成 16 进制需要 32 个字符
int k = 0; // 表示转换结果中对应的字符位置
for (int i = 0; i < 16; i++) { // 从第一个字节开始,对 MD5 的每一个字节
// 转换成 16 进制字符的转换
byte byte0 = tmp[i]; // 取第 i 个字节
str[k++] = hexDigits[byte0 >>> 4 & 0xf]; // 取字节中高 4 位的数字转换,
// >>> 为逻辑右移,将符号位一起右移
str[k++] = hexDigits[byte0 & 0xf]; // 取字节中低 4 位的数字转换
}
s = new String(str); // 换后的结果转换为字符串
} catch (Exception e) {
e.printStackTrace();
}
return s;
}
package com.xuz.datastruct.csdn2;
import java.security.MessageDigest;
public class TestMD5 {
public static void main(String xu[]) {
byte[] keys = { (byte) 0x69, (byte) 0x70, (byte) 0x68, (byte) 0x6F,
(byte) 0x6E, (byte) 0x65, (byte) 0x00, (byte) 0x00,
(byte) 0x33, (byte) 0x30, (byte) 0x35, (byte) 0x20,
(byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x00,
(byte) 0x69, (byte) 0x70, (byte) 0x68, (byte) 0x6F,
(byte) 0x6E, (byte) 0x65, (byte) 0x00, (byte) 0x00 };
System.out.println(md5(new String(keys)));
}
public static String md5(String source) {
StringBuffer sb = new StringBuffer(32);
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] array = md.digest(source.getBytes("utf-8"));
for (int i = 0; i < array.length; i++) {
sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100)
.toUpperCase().substring(1, 3));
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return sb.toString();
}
}