代码之家  ›  专栏  ›  技术社区  ›  hal9000

如何在SAML响应中将X509证书用作公钥

  •  2
  • hal9000  · 技术社区  · 6 年前

    我在SP方面工作。我们有一个来自IDP的SAML2响应。

    它类似于下面的示例:

    SAML: Why is the certificate within the Signature?

    现在,我使用OpenSaml2来解析和处理这个xml文件中的内容。

    我需要从响应中取出证书并将其用作凭据。

    到目前为止,我已经做到了:

    Response response = (Response) xmlObject;
    SAMLSignatureProfileValidator profileValidator = new 
    SAMLSignatureProfileValidator();
    Signature signature = response.getSignature();
    Credential credential = null;
    profileValidator.validate(signature);
    SignatureValidator validator = new SignatureValidator(credential);
    validator.validate(signature);
    

    在上面的代码中,凭证暂时为“null”,但我需要它是公钥,它位于证书中。你知道我该怎么做吗?

    有人告诉我们opensaml2有KeyInfoCredentialResolver这样的方法来帮助实现这一点,但还没有看到这一点的简单实现。

    1 回复  |  直到 6 年前
        1
  •  2
  •   hal9000    6 年前

    我可以通过以下方式解决此问题:

    X509Certificate certificate = signature.getKeyInfo().getX509Datas().get(0).getX509Certificates().get(0);
    
            if (certificate != null) {
                //Converts org.opensaml.xml.signature.X509Certificate to java.security.cert.Certificate
                String lexicalXSDBase64Binary = certificate.getValue();
                byte[] decoded = DatatypeConverter.parseBase64Binary(lexicalXSDBase64Binary);
    
                try {
                    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
                    Certificate cert = certFactory.generateCertificate(new ByteArrayInputStream(decoded));
                    return cert;