亲宝软件园·资讯

展开

Java加密 消息摘要算法MAC实现详解

人气:0

MAC是消息摘要算法的第三种实现方式,另外两种方式分别为:MD2\4\5、SHA。

MAC的jdk实现:1、默认密钥方式

private static void MAC_JDK(){
  try {
   KeyGenerator keyGenerator = KeyGenerator.getInstance("HmacMD5");//初始化KeyGenerator
   SecretKey secretKey = keyGenerator.generateKey();//产生密钥
   byte[] key = secretKey.getEncoded();//获得默认密钥
   
   SecretKey restorSecretKey = new SecretKeySpec(key, "HmacMD5");//还原密钥
   Mac mac = Mac.getInstance(restorSecretKey.getAlgorithm());//示例化MAC
   mac.init(restorSecretKey);//初始化MAC
   byte[] hmacMD5Bytes = mac.doFinal(src.getBytes());//执行摘要
   System.out.println("hmacMD5Byte : "+Hex.encodeHexString(hmacMD5Bytes));
  } catch (Exception e) {
   e.printStackTrace();
  } 
 }

2、动态密钥方式:

private static void MAC_JDK_dongtai(){
  try {
   byte[] key = Hex.decodeHex(new char[]{'a','a','a','a','a','a','a','a','a','a'});//动态获得密钥
   
   SecretKey restorSecretKey = new SecretKeySpec(key, "HmacMD5");//还原密钥
   Mac mac = Mac.getInstance(restorSecretKey.getAlgorithm());//示例化MAC
   mac.init(restorSecretKey);//初始化MAC
   byte[] hmacMD5Bytes = mac.doFinal(src.getBytes());//执行摘要
   System.out.println("hmacMD5Byte : "+Hex.encodeHexString(hmacMD5Bytes));
  } catch (Exception e) {
   e.printStackTrace();
  } 
 }

MAC的BC实现:

private static void MAC_BC(){
  HMac hmac = new HMac(new MD5Digest());
  hmac.init(new KeyParameter(org.bouncycastle.util.encoders.Hex.decode("aaaaaaaaaa")));
  hmac.update(src.getBytes(), 0, src.getBytes().length);
  
  byte[] mac_BC_Byte = new byte[hmac.getMacSize()];//执行摘要
  hmac.doFinal(mac_BC_Byte, 0);
  System.out.println("mac_BC_Byte : "+Hex.encodeHexString(mac_BC_Byte));
 }

到今天JAVA中的Base64、对称加密、消息摘要加密的实现总结就完工了,如果哪位对此感兴趣,还望多多交流。(1453296946@qq.com)

您可能感兴趣的文章:

加载全部内容

相关教程
猜你喜欢
用户评论