使用A256KW算法生成JWE Token时遇未知算法错误求助
解决A256KW算法生成JWE Token的不支持错误
错误信息
org.jose4j.lang.InvalidAlgorithmException: A256KW is an unknown,
unsupported or unavailable alg algorithm (not one of [RSA1_5,
RSA-OAEP, RSA-OAEP-256, dir, A128KW, ECDH-ES, ECDH-ES+A128KW,
PBES2-HS256+A128KW, A128GCMKW]).
问题原因
jose4j库默认依赖JDK自带加密组件,而JDK原生不提供A256KW算法的实现,必须引入BouncyCastle作为额外加密提供者才能启用该算法。
解决步骤
添加BouncyCastle依赖
Maven项目在pom.xml中加入:<dependency> <groupId>org.bouncycastle</groupId> <artifactId>bcprov-jdk15on</artifactId> <version>1.70</version> </dependency>Gradle项目添加:
implementation 'org.bouncycastle:bcprov-jdk15on:1.70'注册BouncyCastle安全提供者
在生成JWE Token的代码逻辑前,加入注册代码:import org.bouncycastle.jce.provider.BouncyCastleProvider; import java.security.Security; Security.addProvider(new BouncyCastleProvider());配置JWE生成器使用A256KW
确保JWE生成器的算法约束包含A256KW,示例代码:JwtConsumerBuilder consumerBuilder = new JwtConsumerBuilder() .setAllowedAlgorithms(AlgorithmConstraints.ConstraintType.WHITELIST, KeyManagementAlgorithmIdentifiers.A256KW) // 其他必要配置 .build();
内容的提问来源于stack exchange,提问作者Tanmay Naik
相关产品推荐
相关产品推荐

