MAC算法主要用于消息验证
以下为算法实现:
import javax.crypto.KeyGenerator; import javax.crypto.Mac; import javax.crypto.SecretKey; import javax.xml.bind.annotation.adapters.HexBinaryAdapter; public class Main { static String src = "Hello,sahadev!"; public static void main(String[] args) { HmacMD5(); } public static void HmacMD5() { try { // 获取密钥生成器 KeyGenerator keyGenerator = KeyGenerator.getInstance("HmacMD5"); // 生成密钥 SecretKey generateKey = keyGenerator.generateKey(); // 获取"Message Authentication Code" (MAC) algorithm实例 Mac instance = Mac.getInstance(generateKey.getAlgorithm()); // 根据生产的密钥初始化该实例 instance.init(generateKey); // 加密消息 byte[] doFinal = instance.doFinal(src.getBytes()); // 输出加密后的消息 System.out.println("HmacMD5 : " + new HexBinaryAdapter().marshal(doFinal)); } catch (Exception e) { e.printStackTrace(); } } }