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());
默认行为:
-
alg(密钥管理算法)标头默认为RSA-OAEP。 -
enc(内容加密)标头默认为A256GCM。
支持的密钥和算法:
- 您可以使用 RSA 公钥、Elliptic Curve (EC)公钥和对称 secret 密钥来加密声明。
-
RSA-OAEP是默认的 RSA 公钥加密算法。 -
ECDH-ES是默认的 EC 公钥加密算法。 -
A256KW是默认的对称密钥加密算法。
请注意,在创建加密令牌时执行两个加密操作:
-
生成的内容加密密钥是使用提供的密钥和密钥加密算法(如
RSA-OAEP)进行加密。 -
该声明使用内容加密密钥和内容加密算法(如
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();
另外,您可以使用以下属性全局配置算法:
smallrye.jwt.new-token.key-encryption-algorithm=RSA-OAEP-256
smallrye.jwt.new-token.content-encryption-algorithm=A256CBC-HS512
此配置允许更简单的 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();
安全令牌加密建议:
- 当令牌直接使用公共 RSA 或 EC 密钥加密时,无法验证哪个方发送令牌。为解决此问题,最好使用对称 secret 密钥进行直接加密,特别是在将 JWT 用作 Cookie 仅由 Quarkus 端点管理时。
- 要使用 RSA 或 EC 公钥加密令牌,如果有签名密钥,则建议首先为令牌签名。如需更多信息,请参阅 签名声明并加密嵌套的 JWT 令牌 部分。