Java电商平台-开放API接口签名验证(小程序/APP)
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class ApiSignature {
private static final String HMAC_ALGORITHM = "HmacSHA256";
private static final String ENCODING = "UTF-8";
public static String generateSignature(String data, String secretKey) throws Exception {
SecretKeySpec signingKey = new SecretKeySpec(secretKey.getBytes(ENCODING), HMAC_ALGORITHM);
Mac mac = Mac.getInstance(HMAC_ALGORITHM);
mac.init(signingKey);
byte[] rawHmac = mac.doFinal(data.getBytes(ENCODING));
return Base64.getEncoder().encodeToString(rawHmac);
}
public static boolean verifySignature(String data, String signature, String secretKey) throws Exception {
String expectedSignature = generateSignature(data, secretKey);
return expectedSignature.equals(signature);
}
// 示例方法,用于生成签名和验证签名
public static void main(String[] args) {
try {
String data = "your_data_string";
String secretKey = "your_secret_key";
// 生成签名
String signature = generateSignature(data, secretKey);
System.out.println("生成的签名: " + signature);
// 验证签名
boolean isValid = verifySignature(data, signature, secretKey);
System.out.println("签名验证结果: " + isValid);
} catch (Exception e) {
e.printStackTrace();
}
}
}
这段代码提供了一个简单的Java类,用于生成和验证使用HMAC-SHA256算法的API签名。在实际应用中,你需要将your_data_string
和your_secret_key
替换成实际的数据和密钥,并根据具体的API要求进行适当的调整。
评论已关闭