亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 RSA512 算法創建簽名的 JWT

如何使用 RSA512 算法創建簽名的 JWT

不負相思意 2023-03-17 13:49:17
我試圖創建 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 密鑰
查看完整描述

1 回答

?
冉冉說

TA貢獻1877條經驗 獲得超1個贊

最初我沒有提供 Base64 編碼的 RSAkey ,我將它再次編碼為 base64 ,這就是我收到此錯誤的原因。


java.lang.IllegalArgumentException:必須使用 RSA 私鑰計算 RSA 簽名。類型為 javax.crypto.spec.SecretKeySpec 的指定密鑰不是 RSA 私鑰。


每當我提供 RSAKey base 64 編碼或字節碼私鑰時,我都會回到錯誤之下


只能為 HMAC 簽名指定 Base64 編碼的密鑰字節。如果使用 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 證書加載私鑰。


查看完整回答
反對 回復 2023-03-17
  • 1 回答
  • 0 關注
  • 233 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號