生成签名(示例)
生成签名代码示例如下:
bizName=demo
appId=default
workspaceId=default
uid=test1234
timestamp=1561014940059(当前时间 + 有效期 N 毫秒)
Java
安全加签的 Java 代码示例如下:
public class EncryptUtils {
public static void main(String[] args) {
// bizName
String bizName = "demo";
// appId
String appId = "default";
// workspaceId
String workspaceId = "default";
// uid
String uid = "test1234";
// 签名有效期(ms),比如 5 分钟
long expire = 5 * 60 * 1000L;
// 签名生效截止时间: 当前时间 + 有效期
long expireTime = System.currentTimeMillis() + expire;
String str = bizName + appId + workspaceId + uid + expireTime;
// 分配的密钥
String key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
// 生成签名
String sign = EncryptUtils.encryptByPrivate(str, EncryptUtils.getPrivateKey(key));
}
//RSA 私钥加密
public static String encryptByPrivate(String content, PrivateKey privateKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
return Base64.getEncoder().encodeToString(cipher.doFinal(content.getBytes("UTF-8")));
}
//将 base64 编码后的 RSA 私钥字符串转成 PrivateKey 实例
public static PrivateKey getPrivateKey(String privateKey) throws Exception {
byte[] keyBytes = Base64.getDecoder().decode(privateKey);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return keyFactory.generatePrivate(keySpec);
}
}