2.4. 加密声明


您可以立即加密声明,或者在设置 JSON Web 加密(JWE) 标头后加密声明,类似于如何签署声明。但是,加密声明始终需要一个 jwe () 转换为 JwtEncryptionBuilder,因为 API 被优化以支持签名和内部签名操作。

import io.smallrye.jwt.build.Jwt;
...

// Encrypt the claims using an RSA public key loaded from the location specified by the 'smallrye.jwt.encrypt.key.location' property.
// The default key encryption algorithm is RSA-OAEP.

String jwt1 = Jwt.claims("/tokenClaims.json").jwe().encrypt();

// Set the headers and encrypt the claims by using an RSA public key loaded in the code (the implementation of this method is omitted).
// The default key encryption algorithm is A256KW.
String jwt2 = Jwt.claims("/tokenClaims.json").jwe().header("custom-header", "custom-value").encrypt(getSecretKey());
Copy to Clipboard Toggle word wrap

默认行为:

  • alg (密钥管理算法)标头默认为 RSA-OAEP
  • enc (内容加密)标头默认为 A256GCM

支持的密钥和算法:

  • 您可以使用 RSA 公钥、Elliptic Curve (EC)公钥和对称 secret 密钥来加密声明。
  • RSA-OAEP 是默认的 RSA 公钥加密算法。
  • ECDH-ES 是默认的 EC 公钥加密算法。
  • A256KW 是默认的对称密钥加密算法。

请注意,在创建加密令牌时执行两个加密操作:

  1. 生成的内容加密密钥是使用提供的密钥和密钥加密算法(如 RSA-OAEP )进行加密。
  2. 该声明使用内容加密密钥和内容加密算法(如 A256GCM )进行加密。

您可以使用 JwtEncryptionBuilder API 自定义密钥和证书算法。例如:

import io.smallrye.jwt.KeyEncryptionAlgorithm;
import io.smallrye.jwt.ContentEncryptionAlgorithm;
import io.smallrye.jwt.build.Jwt;

// Encrypt the claims using an RSA public key loaded from the location set with a 'smallrye.jwt.encrypt.key.location' property.
// Key encryption algorithm is RSA-OAEP-256. The content encryption algorithm is A256CBC-HS512.

String jwt = Jwt.subject("Bob").jwe()
    .keyAlgorithm(KeyEncryptionAlgorithm.RSA_OAEP_256)
    .contentAlgorithm(ContentEncryptionAlgorithm.A256CBC_HS512)
    .encrypt();
Copy to Clipboard Toggle word wrap

另外,您可以使用以下属性全局配置算法:

smallrye.jwt.new-token.key-encryption-algorithm=RSA-OAEP-256
smallrye.jwt.new-token.content-encryption-algorithm=A256CBC-HS512
Copy to Clipboard Toggle word wrap

此配置允许更简单的 API 序列:

import io.smallrye.jwt.build.Jwt;

// Encrypt the claims by using an RSA public key loaded from the location set with a 'smallrye.jwt.encrypt.key.location' property.
// Key encryption algorithm is RSA-OAEP-256. The content encryption algorithm is A256CBC-HS512.
String jwt = Jwt.subject("Bob").encrypt();
Copy to Clipboard Toggle word wrap

安全令牌加密建议:

  • 当令牌直接使用公共 RSA 或 EC 密钥加密时,无法验证哪个方发送令牌。为解决此问题,最好使用对称 secret 密钥进行直接加密,特别是在将 JWT 用作 Cookie 仅由 Quarkus 端点管理时。
  • 要使用 RSA 或 EC 公钥加密令牌,如果有签名密钥,则建议首先为令牌签名。如需更多信息,请参阅 签名声明并加密嵌套的 JWT 令牌 部分。
Red Hat logoGithubredditYoutubeTwitter

学习

尝试、购买和销售

社区

关于红帽文档

通过我们的产品和服务,以及可以信赖的内容,帮助红帽用户创新并实现他们的目标。 了解我们当前的更新.

让开源更具包容性

红帽致力于替换我们的代码、文档和 Web 属性中存在问题的语言。欲了解更多详情,请参阅红帽博客.

關於紅帽

我们提供强化的解决方案,使企业能够更轻松地跨平台和环境(从核心数据中心到网络边缘)工作。

Theme

© 2026 Red Hat
返回顶部