org.opensaml.xmlsec.signature.KeyInfo Java Examples

The following examples show how to use org.opensaml.xmlsec.signature.KeyInfo. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@Test
public void testIdPMetadata() throws Exception {
    String url = "https://localhost:" + getIdpHttpsPort()
        + "/fediz-idp/metadata?protocol=saml";

    final WebClient webClient = new WebClient();
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getOptions().setSSLClientCertificate(
        this.getClass().getClassLoader().getResource("client.jks"), "storepass", "jks");

    final XmlPage rpPage = webClient.getPage(url);
    final String xmlContent = rpPage.asXml();
    Assert.assertTrue(xmlContent.startsWith("<md:EntityDescriptor"));

    // Now validate the Signature
    Document doc = rpPage.getXmlDocument();

    doc.getDocumentElement().setIdAttributeNS(null, "ID", true);

    Node signatureNode =
        DOMUtils.getChild(doc.getDocumentElement(), "Signature");
    Assert.assertNotNull(signatureNode);

    XMLSignature signature = new XMLSignature((Element)signatureNode, "");
    org.apache.xml.security.keys.KeyInfo ki = signature.getKeyInfo();
    Assert.assertNotNull(ki);
    Assert.assertNotNull(ki.getX509Certificate());

    Assert.assertTrue(signature.checkSignatureValue(ki.getX509Certificate()));

    webClient.close();
}
 
Example #2
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
private static void signAuthnRequest(SignableSAMLObject signableObject) throws Exception {
    Crypto crypto = CryptoFactory.getInstance("stsKeystoreA.properties");

    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias("realma");
    X509Certificate[] issuerCerts = crypto.getX509Certificates(cryptoType);

    String sigAlgo = SSOConstants.RSA_SHA1;

    // Get the private key
    PrivateKey privateKey = crypto.getPrivateKey("realma", "realma");

    // Create the signature
    Signature signature = OpenSAMLUtil.buildSignature();
    signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
    signature.setSignatureAlgorithm(sigAlgo);

    BasicX509Credential signingCredential = new BasicX509Credential(issuerCerts[0], privateKey);

    signature.setSigningCredential(signingCredential);

    X509KeyInfoGeneratorFactory kiFactory = new X509KeyInfoGeneratorFactory();
    kiFactory.setEmitEntityCertificate(true);

    try {
        KeyInfo keyInfo = kiFactory.newInstance().generate(signingCredential);
        signature.setKeyInfo(keyInfo);
    } catch (org.opensaml.security.SecurityException ex) {
        throw new Exception(
                "Error generating KeyInfo from signing credential", ex);
    }

    signableObject.setSignature(signature);
    signableObject.releaseDOM();
    signableObject.releaseChildrenDOM(true);

}
 
Example #3
Source File: SamlMetadataServiceFunction.java    From armeria with Apache License 2.0 4 votes vote down vote up
private static KeyDescriptor buildKeyDescriptorElement(UsageType type, @Nullable KeyInfo key) {
    final KeyDescriptor descriptor = build(KeyDescriptor.DEFAULT_ELEMENT_NAME);
    descriptor.setUse(type);
    descriptor.setKeyInfo(key);
    return descriptor;
}
 
Example #4
Source File: SAMLProtocolResponseValidator.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * Validate the response signature
 */
private void validateResponseSignature(
    Signature signature,
    Document doc,
    Crypto sigCrypto,
    CallbackHandler callbackHandler
) throws WSSecurityException {
    RequestData requestData = new RequestData();
    requestData.setSigVerCrypto(sigCrypto);
    WSSConfig wssConfig = WSSConfig.getNewInstance();
    requestData.setWssConfig(wssConfig);
    requestData.setCallbackHandler(callbackHandler);
    requestData.setWsDocInfo(new WSDocInfo(doc));

    SAMLKeyInfo samlKeyInfo = null;

    KeyInfo keyInfo = signature.getKeyInfo();
    if (keyInfo != null) {
        try {
            samlKeyInfo =
                SAMLUtil.getCredentialFromKeyInfo(
                    keyInfo.getDOM(), new WSSSAMLKeyInfoProcessor(requestData), sigCrypto
                );
        } catch (WSSecurityException ex) {
            LOG.log(Level.FINE, "Error in getting KeyInfo from SAML Response: " + ex.getMessage(), ex);
            throw ex;
        }
    } else if (!keyInfoMustBeAvailable) {
        samlKeyInfo = createKeyInfoFromDefaultAlias(sigCrypto);
    }
    if (samlKeyInfo == null) {
        LOG.warning("No KeyInfo supplied in the SAMLResponse signature");
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    // Validate Signature against profiles
    validateSignatureAgainstProfiles(signature, samlKeyInfo);

    // Now verify trust on the signature
    Credential trustCredential = new Credential();
    trustCredential.setPublicKey(samlKeyInfo.getPublicKey());
    trustCredential.setCertificates(samlKeyInfo.getCerts());

    try {
        signatureValidator.validate(trustCredential, requestData);
    } catch (WSSecurityException e) {
        LOG.log(Level.FINE, "Error in validating signature on SAML Response: " + e.getMessage(), e);
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }
}
 
Example #5
Source File: SAMLProtocolResponseValidator.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * Validate an internal Assertion
 */
private void validateAssertion(
    SamlAssertionWrapper assertion,
    Crypto sigCrypto,
    CallbackHandler callbackHandler,
    Document doc,
    boolean signedResponse
) throws WSSecurityException {
    Credential credential = new Credential();
    credential.setSamlAssertion(assertion);

    RequestData requestData = new RequestData();
    requestData.setSigVerCrypto(sigCrypto);
    WSSConfig wssConfig = WSSConfig.getNewInstance();
    requestData.setWssConfig(wssConfig);
    requestData.setCallbackHandler(callbackHandler);

    if (assertion.isSigned()) {
        if (assertion.getSaml1() != null) {
            assertion.getSaml1().getDOM().setIdAttributeNS(null, "AssertionID", true);
        } else {
            assertion.getSaml2().getDOM().setIdAttributeNS(null, "ID", true);
        }

        // Verify the signature
        try {
            Signature sig = assertion.getSignature();
            WSDocInfo docInfo = new WSDocInfo(sig.getDOM().getOwnerDocument());
            requestData.setWsDocInfo(docInfo);

            SAMLKeyInfo samlKeyInfo = null;

            KeyInfo keyInfo = sig.getKeyInfo();
            if (keyInfo != null) {
                samlKeyInfo = SAMLUtil.getCredentialFromKeyInfo(
                    keyInfo.getDOM(), new WSSSAMLKeyInfoProcessor(requestData), sigCrypto
                );
            } else if (!keyInfoMustBeAvailable) {
                samlKeyInfo = createKeyInfoFromDefaultAlias(sigCrypto);
            }

            if (samlKeyInfo == null) {
                LOG.warning("No KeyInfo supplied in the SAMLResponse assertion signature");
                throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
            }

            assertion.verifySignature(samlKeyInfo);

            assertion.parseSubject(
                new WSSSAMLKeyInfoProcessor(requestData),
                requestData.getSigVerCrypto(),
                requestData.getCallbackHandler()
            );
        } catch (WSSecurityException e) {
            LOG.log(Level.FINE, "Assertion failed signature validation", e);
            throw e;
        }
    }

    // Validate the Assertion & verify trust in the signature
    try {
        SamlSSOAssertionValidator assertionValidator = new SamlSSOAssertionValidator(signedResponse);
        assertionValidator.validate(credential, requestData);
    } catch (WSSecurityException ex) {
        LOG.log(Level.FINE, "Assertion validation failed: " + ex.getMessage(), ex);
        throw ex;
    }
}
 
Example #6
Source File: SAMLResponseValidatorTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * Sign a SAML Response
 * @throws Exception
 */
private void signResponse(
    Response response,
    String issuerKeyName,
    String issuerKeyPassword,
    Crypto issuerCrypto,
    boolean useKeyInfo
) throws Exception {
    //
    // Create the signature
    //
    Signature signature = OpenSAMLUtil.buildSignature();
    signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);

    // prepare to sign the SAML token
    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias(issuerKeyName);
    X509Certificate[] issuerCerts = issuerCrypto.getX509Certificates(cryptoType);
    if (issuerCerts == null) {
        throw new Exception(
                "No issuer certs were found to sign the SAML Assertion using issuer name: "
                        + issuerKeyName);
    }

    String sigAlgo = SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1;
    String pubKeyAlgo = issuerCerts[0].getPublicKey().getAlgorithm();

    if ("DSA".equalsIgnoreCase(pubKeyAlgo)) {
        sigAlgo = SignatureConstants.ALGO_ID_SIGNATURE_DSA;
    }

    PrivateKey privateKey = issuerCrypto.getPrivateKey(issuerKeyName, issuerKeyPassword);

    signature.setSignatureAlgorithm(sigAlgo);

    BasicX509Credential signingCredential =
        new BasicX509Credential(issuerCerts[0], privateKey);
    signature.setSigningCredential(signingCredential);

    if (useKeyInfo) {
        X509KeyInfoGeneratorFactory kiFactory = new X509KeyInfoGeneratorFactory();
        kiFactory.setEmitEntityCertificate(true);

        try {
            KeyInfo keyInfo = kiFactory.newInstance().generate(signingCredential);
            signature.setKeyInfo(keyInfo);
        } catch (org.opensaml.security.SecurityException ex) {
            throw new Exception(
                    "Error generating KeyInfo from signing credential", ex);
        }
    }

    // add the signature to the assertion
    SignableSAMLObject signableObject = response;
    signableObject.setSignature(signature);
    signableObject.releaseDOM();
    signableObject.releaseChildrenDOM(true);
}
 
Example #7
Source File: SAMLSSOResponseValidatorTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * Sign a SAML Response
 * @throws Exception
 */
private void signResponse(
    Response response,
    String issuerKeyName,
    String issuerKeyPassword,
    Crypto issuerCrypto,
    boolean useKeyInfo
) throws Exception {
    //
    // Create the signature
    //
    Signature signature = OpenSAMLUtil.buildSignature();
    signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);

    // prepare to sign the SAML token
    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias(issuerKeyName);
    X509Certificate[] issuerCerts = issuerCrypto.getX509Certificates(cryptoType);
    if (issuerCerts == null) {
        throw new Exception(
                "No issuer certs were found to sign the SAML Assertion using issuer name: "
                        + issuerKeyName);
    }

    String sigAlgo = SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1;
    String pubKeyAlgo = issuerCerts[0].getPublicKey().getAlgorithm();

    if ("DSA".equalsIgnoreCase(pubKeyAlgo)) {
        sigAlgo = SignatureConstants.ALGO_ID_SIGNATURE_DSA;
    }

    PrivateKey privateKey = issuerCrypto.getPrivateKey(issuerKeyName, issuerKeyPassword);

    signature.setSignatureAlgorithm(sigAlgo);

    BasicX509Credential signingCredential = new BasicX509Credential(issuerCerts[0], privateKey);

    signature.setSigningCredential(signingCredential);

    if (useKeyInfo) {
        X509KeyInfoGeneratorFactory kiFactory = new X509KeyInfoGeneratorFactory();
        kiFactory.setEmitEntityCertificate(true);

        try {
            KeyInfo keyInfo = kiFactory.newInstance().generate(signingCredential);
            signature.setKeyInfo(keyInfo);
        } catch (org.opensaml.security.SecurityException ex) {
            throw new Exception(
                    "Error generating KeyInfo from signing credential", ex);
        }
    }

    // add the signature to the assertion
    SignableSAMLObject signableObject = response;
    signableObject.setSignature(signature);
    signableObject.releaseDOM();
    signableObject.releaseChildrenDOM(true);
}
 
Example #8
Source File: CombinedValidatorTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
private void signResponse(
    Response response,
    String issuerKeyName,
    String issuerKeyPassword,
    Crypto issuerCrypto,
    boolean useKeyInfo
) throws Exception {
    //
    // Create the signature
    //
    Signature signature = OpenSAMLUtil.buildSignature();
    signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);

    // prepare to sign the SAML token
    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias(issuerKeyName);
    X509Certificate[] issuerCerts = issuerCrypto.getX509Certificates(cryptoType);
    if (issuerCerts == null) {
        throw new Exception(
            "No issuer certs were found to sign the SAML Assertion using issuer name: " + issuerKeyName);
    }

    String sigAlgo = SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1;
    String pubKeyAlgo = issuerCerts[0].getPublicKey().getAlgorithm();

    if ("DSA".equalsIgnoreCase(pubKeyAlgo)) {
        sigAlgo = SignatureConstants.ALGO_ID_SIGNATURE_DSA;
    }

    PrivateKey privateKey = issuerCrypto.getPrivateKey(issuerKeyName, issuerKeyPassword);

    signature.setSignatureAlgorithm(sigAlgo);

    BasicX509Credential signingCredential =
        new BasicX509Credential(issuerCerts[0], privateKey);
    signature.setSigningCredential(signingCredential);

    if (useKeyInfo) {
        X509KeyInfoGeneratorFactory kiFactory = new X509KeyInfoGeneratorFactory();
        kiFactory.setEmitEntityCertificate(true);

        try {
            KeyInfo keyInfo = kiFactory.newInstance().generate(signingCredential);
            signature.setKeyInfo(keyInfo);
        } catch (org.opensaml.security.SecurityException ex) {
            throw new Exception("Error generating KeyInfo from signing credential", ex);
        }
    }

    // add the signature to the assertion
    SignableSAMLObject signableObject = response;
    signableObject.setSignature(signature);
    signableObject.releaseDOM();
    signableObject.releaseChildrenDOM(true);
}
 
Example #9
Source File: AuthnRequestParser.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
/**
 * Validate the AuthnRequest or LogoutRequest signature
 */
private void validateRequestSignature(
    Signature signature,
    Crypto sigCrypto
) throws WSSecurityException {
    RequestData requestData = new RequestData();
    requestData.setSigVerCrypto(sigCrypto);
    WSSConfig wssConfig = WSSConfig.getNewInstance();
    requestData.setWssConfig(wssConfig);
    // requestData.setCallbackHandler(callbackHandler);

    SAMLKeyInfo samlKeyInfo = null;

    KeyInfo keyInfo = signature.getKeyInfo();
    if (keyInfo != null) {
        try {
            Document doc = signature.getDOM().getOwnerDocument();
            requestData.setWsDocInfo(new WSDocInfo(doc));
            samlKeyInfo =
                SAMLUtil.getCredentialFromKeyInfo(
                    keyInfo.getDOM(), new WSSSAMLKeyInfoProcessor(requestData), sigCrypto
                );
        } catch (WSSecurityException ex) {
            LOG.debug("Error in getting KeyInfo from SAML AuthnRequest: {}", ex.getMessage(), ex);
            throw ex;
        }
    }

    if (samlKeyInfo == null) {
        LOG.debug("No KeyInfo supplied in the AuthnRequest signature");
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    // Validate Signature against profiles
    validateSignatureAgainstProfiles(signature, samlKeyInfo);

    // Now verify trust on the signature
    Credential trustCredential = new Credential();
    trustCredential.setPublicKey(samlKeyInfo.getPublicKey());
    trustCredential.setCertificates(samlKeyInfo.getCerts());

    try {
        Validator signatureValidator = new SignatureTrustValidator();
        signatureValidator.validate(trustCredential, requestData);
    } catch (WSSecurityException e) {
        LOG.debug("Error in validating signature on SAML AuthnRequest: {}", e.getMessage(), e);
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }
}