Java安全与应用部署全解析
1. Java安全基础
1.1 消息认证码计算
消息认证码(MAC)用于验证数据的完整性和真实性。以下是一个创建 Mac
类实例并计算数据消息认证码的示例代码:
import java.security.*;
import javax.crypto.*;
import java.io.*;
public class MacExample {
public static void main(String args[]) {
try {
String inputString = "Test input string";
KeyGenerator keyGen = KeyGenerator.getInstance("HmacMD5");
SecretKey secretKey = keyGen.generateKey();
Mac mac = Mac.getInstance(secretKey.getAlgorithm());
mac.init(secretKey);
// the Mac class needs data in byte format
byte[] byteData = inputString.getBytes("UTF8");
// Compute the MAC for the data all in one operation