2025-10-08 13:46:21 +08:00

80 lines
2.8 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.heyu.api.alibaba;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;
public class AliyunCDNAuthA {
/**
* 生成阿里云CDN鉴权方式A的加密URL
*
* @param filePath 文件路径,以/开头,如 "/video/test.mp4"
* @param expiresInSeconds 过期时间(从当前算起的秒数)
* @return 完整的加密URL
*/
public static String generateAuthUrl(String privateKey,String domainName,String filePath, long expiresInSeconds) {
try {
// 1. 生成时间戳(当前时间 + 过期时间)
long timestamp = (System.currentTimeMillis() / 1000) + expiresInSeconds;
// 2. 生成随机数去掉UUID中的短横线
String rand = UUID.randomUUID().toString().replace("-", "");
// 3. 设置uid为0
String uid = "0";
// 4. 计算md5hash
String md5hash = calculateMd5Hash(privateKey,filePath, timestamp, rand, uid);
// 5. 构建鉴权URL
return "http://" + domainName + filePath +
"?auth_key=" + timestamp + "-" + rand + "-" + uid + "-" + md5hash;
} catch (Exception e) {
throw new RuntimeException("生成鉴权URL失败", e);
}
}
/**
* 计算MD5哈希值
*/
private static String calculateMd5Hash(String privateKey,String filePath, long timestamp, String rand, String uid)
throws NoSuchAlgorithmException {
// 构造签名字符串
String signString = filePath + "-" + timestamp + "-" + rand + "-" + uid + "-" + privateKey;
// 计算MD5
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] digest = md.digest(signString.getBytes());
// 转换为十六进制字符串
StringBuilder hexString = new StringBuilder();
for (byte b : digest) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
/**
* 使用示例
*/
public static void main(String[] args) {
// 初始化鉴权对象
String privateKey = "heyuquyixiao123456"; // 替换为你的密钥
String domainName = "heyuimage.ihzhy.com"; // 替换为你的CDN域名
// 生成鉴权URL有效时间30分钟1800秒
String filePath = "/ccc.jpeg";
String authUrl = AliyunCDNAuthA.generateAuthUrl(privateKey,domainName,filePath, 1800);
System.out.println("生成的鉴权URL: " + authUrl);
}
}