全部产品

代码示例

更新时间:2020-06-18 10:04:07

生成签名(示例)

  1. bizName=demo
  2. appId=default
  3. workspaceId=default
  4. uid=test1234
  5. timestamp=1561014940059(当前时间 + 有效期 N 毫秒)

JAVA

  1. public class EncryptUtils {
  2. public static void main(String[] args) {
  3. // bizName
  4. String bizName = "demo";
  5. // appId
  6. String appId = "default";
  7. // workspaceId
  8. String workspaceId = "default";
  9. // uid
  10. String uid = "test1234";
  11. // 签名有效期(ms),比如 5 分钟
  12. long expire = 5 * 60 * 1000L;
  13. // 签名生效截止时间: 当前时间 + 有效期
  14. long expireTime = System.currentTimeMillis() + expire;
  15. String str = bizName + appId + workspaceId + uid + expireTime;
  16. // 分配的密钥
  17. String key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
  18. // 生成签名
  19. String sign = EncryptUtils.encryptByPrivate(str, EncryptUtils.getPrivateKey(key));
  20. }
  21. //RSA 私钥加密
  22. public static String encryptByPrivate(String content, PrivateKey privateKey) throws Exception {
  23. Cipher cipher = Cipher.getInstance("RSA");
  24. cipher.init(Cipher.ENCRYPT_MODE, privateKey);
  25. return Base64.getEncoder().encodeToString(cipher.doFinal(content.getBytes("UTF-8")));
  26. }
  27. //将 base64 编码后的 RSA 私钥字符串转成 PrivateKey 实例
  28. public static PrivateKey getPrivateKey(String privateKey) throws Exception {
  29. byte[] keyBytes = Base64.getDecoder().decode(privateKey);
  30. PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
  31. KeyFactory keyFactory = KeyFactory.getInstance("RSA");
  32. return keyFactory.generatePrivate(keySpec);
  33. }
  34. }