使用OpenSaml-2解密SAML断言遇OAEPPadding不支持问题求助
解决SAML断言解密时的
NoSuchPaddingException: OAEPPadding异常 问题原因
你遇到的异常是因为SunMSCAPI(Java调用Windows证书存储的JCA提供者)不支持RSA OAEP填充算法,而ADFS默认可能采用了OAEP作为断言加密的填充方式,导致私钥解密时无法识别该填充类型。
解决方案
1. 修改ADFS的加密配置,使用SunMSCAPI支持的填充方式
ADFS允许针对信赖方配置加密算法,将密钥传输算法改为SunMSCAPI支持的RSA-PKCS1(PKCS#1 v1.5填充):
- 打开ADFS管理控制台,找到对应的信赖方信任
- 右键选择属性,切换到加密标签页
- 点击添加,选择
RSA 1.5作为密钥传输算法并设为首选 - 移除原有的
RSA-OAEP算法,保存配置
2. 导出私钥到标准密钥库,改用默认JCA提供者
绕过SunMSCAPI,将Windows证书存储中的私钥导出为PFX(PKCS#12)格式,在Java中加载该密钥库后使用默认SunJCE提供者处理解密:
步骤1:导出PFX证书
- 打开MMC证书管理单元,找到目标证书,右键选择所有任务 > 导出
- 选择是,导出私钥,按向导完成导出并设置密码保护PFX文件
步骤2:修改代码加载PFX密钥库
public static Assertion getDecryptedAssertion(EncryptedAssertion encryptedAssertion, String pfxPath, String pfxPassword) throws Exception { ChainingEncryptedKeyResolver keyResolver = new ChainingEncryptedKeyResolver(); keyResolver.getResolverChain().add(new InlineEncryptedKeyResolver()); keyResolver.getResolverChain().add(new EncryptedElementTypeEncryptedKeyResolver()); keyResolver.getResolverChain().add(new SimpleRetrievalMethodEncryptedKeyResolver()); // 加载PFX密钥库 KeyStore keyStore = KeyStore.getInstance("PKCS12"); try (FileInputStream fis = new FileInputStream(pfxPath)) { keyStore.load(fis, pfxPassword.toCharArray()); } // 获取私钥(若证书别名已知可直接指定,此处为遍历示例) String alias = keyStore.aliases().nextElement(); PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, pfxPassword.toCharArray()); X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias); BasicX509Credential decryptionCredential = new BasicX509Credential(); decryptionCredential.setPrivateKey(privateKey); decryptionCredential.setCertificate(cert); StaticKeyInfoCredentialResolver resolver = new StaticKeyInfoCredentialResolver(decryptionCredential); // 创建解密器,不指定SunMSCAPI,使用默认SunJCE提供者 Decrypter decrypter = new Decrypter(null, resolver, keyResolver); decrypter.setRootInNewDocument(true); // 解密断言 Assertion decryptedAssertion = null; try { decryptedAssertion = decrypter.decrypt(encryptedAssertion); } catch (Exception e) { throw new Exception("Error while decrypting the saml response ASSERTION.", e); } return decryptedAssertion; }
3. 升级依赖库以优化SunMSCAPI支持
若必须使用Windows证书存储,可尝试升级xmlsec到2.2.x版本(注意与OpenSAML 2的兼容性),新版本对SunMSCAPI的OAEP填充支持有所改进。同时确保JDK版本不低于1.8u151,后续JDK版本对SunMSCAPI的加密算法支持更完善。
内容的提问来源于stack exchange,提问作者Mounika
相关产品推荐
相关产品推荐

