请问,问什么用MD5,SHA,HmacMD5加密同一数据后不一致?
import java.security.MessageDigest;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class Coder {
public static final String KEY_SHA="SHA";
public static final String KEY_MD5="MD5";
public static final String KEY_MAC="HmacMD5";
public static byte[] encryptMD5(byte[] data) throws Exception
{
MessageDigest md5=MessageDigest.getInstance(KEY_MD5);
md5.update(data);
return md5.digest();
}
public static byte[] encryptSHA(byte[] data) throws Exception
{
MessageDigest sha=MessageDigest.getInstance(KEY_SHA);
sha.update(data);
return sha.digest();
}
public static String initMacKey() throws Exception
{
KeyGenerator kg=KeyGenerator.getInstance(KEY_MAC);
SecretKey sk=kg.generateKey();
return encryptBASE64(sk.getEncoded());
}
public static byte[] encryptHMAC(byte[] data,String key) throws Exception
{
SecretKey sk=new SecretKeySpec(decryptBASE64(key),KEY_MAC);
Mac mac=Mac.getInstance(sk.getAlgorithm());
mac.init(sk);
return mac.doFinal(data);
}
public static void main(String[] args) throws Exception {
String s="简单加密";
byte[] sb=s.getBytes();
System.out.println("MD5加密同一内容:");
System.out.println(encryptMD5(sb));
System.out.println(encryptMD5(sb));
System.out.println("SHA加密同一内容:");
System.out.println(encryptSHA(sb));
System.out.println(encryptSHA(sb));
System.out.println("Hmac加密同一内容:");
String key=initMacKey();
System.out.println(encryptHMAC(sb,key));
System.out.println(encryptHMAC(sb,key));
}
}
运行结果:
MD5加密同一内容:
[B@1e0be38
[B@1e859c0
SHA加密同一内容:
[B@1ded0fd
[B@16a9d42
Hmac加密同一内容:
[B@1968e23
[B@14da8f4
------解决方案--------------------
你输出的是Byte数组的地址。。。。
数组是没有重写toString的