Kis*_*tty 5 java jwt spring-boot jwt-auth
我试图创建 JWT(“JOT”)令牌以使我的 api 调用真实。当我尝试使用 RSA512 签名创建令牌时,我收到一条错误消息
java.lang.IllegalArgumentException:必须使用 RSA PrivateKey 计算 RSA 签名。指定的 javax.crypto.spec.SecretKeySpec 类型的密钥不是 RSA PrivateKey。
我正在使用以下代码:
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);
Run Code Online (Sandbox Code Playgroud)
注意:我的“SECRET_KEY”是一个字符串,它是一个在线随机生成的私钥。我的问题是如何从使用 RSA 密钥大小编码为 4096. 4096 的字符串中获取 Key 对象,因为我使用的是 RSA512 加密,建议对 RSA512 使用 4096 密钥
最初,我没有提供 Base64 编码的 RSAkey,我将其再次编码为 base64 ,这就是我收到此错误的原因。
java.lang.IllegalArgumentException:必须使用 RSA PrivateKey 计算 RSA 签名。javax.crypto.spec.SecretKeySpec 类型的指定密钥不是 RSA PrivateKey。
当我提供 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;
}
Run Code Online (Sandbox Code Playgroud)
提供 java.security.key 类型的私钥并且必须是 RSA 密钥始终是最好的想法。我使用P12证书来加载私钥。
归档时间: |
|
查看次数: |
3528 次 |
最近记录: |