如何使用 RSA512 算法创建签名的 JWT

How to create a signed JWT with RSA512 algorithm

我正在尝试创建 JWT ("JOT") 令牌以使我的 api 呼叫真实。每当我尝试使用 RSA512 签名创建令牌时,我都会收到一条错误消息

java.lang.IllegalArgumentException:必须使用 RSA 私钥计算 RSA 签名。 javax.crypto.spec.SecretKeySpec 类型的指定密钥不是 RSA 私钥。

我正在使用以下代码:

 SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.RS512;

 long nowMillis = System.currentTimeMillis();
  Date now = new Date(nowMillis);
 byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(SECRET_KEY);
 Key signingKey = new SecretKeySpec(apiKeySecretBytes, 
                signatureAlgorithm.getJcaName());

   JwtBuilder builder = Jwts.builder().claim("uuid", 
    id).setIssuedAt(now).setExpiration(new Date(600000))
    .signWith(signatureAlgorithm, signingKey);

注意:我的"SECRET_KEY"是一个字符串,是网上随机生成的私钥。 我的问题是如何从使用 RSA 密钥大小编码为 4096 的字符串中获取密钥对象。 4096 由于我使用的是RSA512加密,建议RSA512使用4096密钥

最初我没有提供 Base64 编码的 RSAkey,我将它再次编码为 base64,这就是我收到此错误的原因。

java.lang.IllegalArgumentException:必须使用 RSA 私钥计算 RSA 签名。类型为 javax.crypto.spec.SecretKeySpec 的指定密钥不是 RSA 私钥。

每当我提供 RSAKey base 64 编码或字节码私钥时,我都会回到错误之下

Base64 编码的密钥字节只能指定用于 HMAC 签名。如果使用 RSA 或椭圆曲线,请改用 signWith(SignatureAlgorithm, Key) 方法。

每当我提供私钥的字符串/字节时,它一直在检查 HMAC 算法。请参阅 JWTBuilder 中的以下代码。

@Override
public JwtBuilder signWith(SignatureAlgorithm alg, byte[] secretKey) {
    Assert.notNull(alg, "SignatureAlgorithm cannot be null.");
    Assert.notEmpty(secretKey, "secret key byte array cannot be null or empty.");
    Assert.isTrue(alg.isHmac(), "Key bytes may only be specified for HMAC signatures.  If using RSA or Elliptic Curve, use the signWith(SignatureAlgorithm, Key) method instead.");
    this.algorithm = alg;
    this.keyBytes = secretKey;
    return this;
}

@Override
public JwtBuilder signWith(SignatureAlgorithm alg, String base64EncodedSecretKey) {
    Assert.hasText(base64EncodedSecretKey, "base64-encoded secret key cannot be null or empty.");
    Assert.isTrue(alg.isHmac(), "Base64-encoded key bytes may only be specified for HMAC signatures.  If using RSA or Elliptic Curve, use the signWith(SignatureAlgorithm, Key) method instead.");
    byte[] bytes = TextCodec.BASE64.decode(base64EncodedSecretKey);
    return signWith(alg, bytes);
}

@Override
public JwtBuilder signWith(SignatureAlgorithm alg, Key key) {
    Assert.notNull(alg, "SignatureAlgorithm cannot be null.");
    Assert.notNull(key, "Key argument cannot be null.");
    this.algorithm = alg;
    this.key = key;
    return this;
}

提供 java.security.key 类型的私钥始终是最好的主意,并且必须是 RSA 密钥。我使用P12证书加载私钥。