org.opensaml.xmlsec.signature.support.SignatureConstants Java Examples

The following examples show how to use org.opensaml.xmlsec.signature.support.SignatureConstants. 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: AuthReqBuilder.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Generate an Signed authentication request with a custom consumer url.
 *
 * @return AuthnRequest Object
 * @throws SSOHostObjectException error when bootstrapping
 */

public AuthnRequest buildSignedAuthRequest(String issuerId, String destination, String acsUrl, boolean isPassive,
        int tenantId, String tenantDomain, String nameIdPolicy) throws SSOHostObjectException {
    Util.doBootstrap();
    AuthnRequest authnRequest = (AuthnRequest) Util.buildXMLObject(AuthnRequest.DEFAULT_ELEMENT_NAME);
    authnRequest.setID(Util.createID());
    authnRequest.setVersion(SAMLVersion.VERSION_20);
    authnRequest.setIssueInstant(new DateTime());
    authnRequest.setIssuer(buildIssuer(issuerId));
    authnRequest.setNameIDPolicy(Util.buildNameIDPolicy(nameIdPolicy));
    if (!StringUtils.isEmpty(acsUrl)) {
        acsUrl = Util.processAcsUrl(acsUrl);
        authnRequest.setAssertionConsumerServiceURL(acsUrl);
    }
    if (isPassive){
        authnRequest.setIsPassive(true);
    }
    authnRequest.setDestination(destination);
    SSOAgentCarbonX509Credential ssoAgentCarbonX509Credential =
            new SSOAgentCarbonX509Credential(tenantId, tenantDomain);
    setSignature(authnRequest, SignatureConstants.ALGO_ID_SIGNATURE_RSA,
            new X509CredentialImpl(ssoAgentCarbonX509Credential));
    return authnRequest;
}
 
Example #2
Source File: MockSamlIdpServer.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
private String createSamlAuthResponse(AuthnRequest authnRequest) {
    try {
        Response response = createSamlElement(Response.class);
        response.setID(nextId());

        if (authnRequest != null) {
            response.setInResponseTo(authnRequest.getID());
        }

        response.setVersion(SAMLVersion.VERSION_20);
        response.setStatus(createStatus(StatusCode.SUCCESS));
        response.setIssueInstant(new DateTime());

        Assertion assertion = createSamlElement(Assertion.class);
        response.getAssertions().add(assertion);

        assertion.setID(nextId());
        assertion.setIssueInstant(new DateTime());
        assertion.setIssuer(createIssuer());

        AuthnStatement authnStatement = createSamlElement(AuthnStatement.class);
        assertion.getAuthnStatements().add(authnStatement);

        authnStatement.setAuthnInstant(new DateTime());
        authnStatement.setSessionIndex(nextId());
        authnStatement.setAuthnContext(createAuthnCotext());

        Subject subject = createSamlElement(Subject.class);
        assertion.setSubject(subject);

        subject.setNameID(createNameID(NameIDType.UNSPECIFIED, authenticateUser));

        if (authnRequest != null) {
            subject.getSubjectConfirmations()
                    .add(createSubjectConfirmation("urn:oasis:names:tc:SAML:2.0:cm:bearer",
                            new DateTime().plusMinutes(1), authnRequest.getID(),
                            authnRequest.getAssertionConsumerServiceURL()));
        } else {
            subject.getSubjectConfirmations().add(createSubjectConfirmation("urn:oasis:names:tc:SAML:2.0:cm:bearer",
                    new DateTime().plusMinutes(1), null, defaultAssertionConsumerService));
        }

        Conditions conditions = createSamlElement(Conditions.class);
        assertion.setConditions(conditions);

        conditions.setNotBefore(new DateTime());
        conditions.setNotOnOrAfter(new DateTime().plusMinutes(1));

        if (authenticateUserRoles != null) {
            AttributeStatement attributeStatement = createSamlElement(AttributeStatement.class);
            assertion.getAttributeStatements().add(attributeStatement);

            Attribute attribute = createSamlElement(Attribute.class);
            attributeStatement.getAttributes().add(attribute);

            attribute.setName("roles");
            attribute.setNameFormat("urn:oasis:names:tc:SAML:2.0:attrname-format:basic");

            for (String role : authenticateUserRoles) {
                attribute.getAttributeValues().add(createXSAny(AttributeValue.DEFAULT_ELEMENT_NAME, role));
            }
        }

        if (signResponses) {
            Signature signature = createSamlElement(Signature.class);
            assertion.setSignature(signature);

            signature.setSigningCredential(this.signingCredential);
            signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1);
            signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);

            XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(assertion).marshall(assertion);

            Signer.signObject(signature);
        }

        String marshalledXml = marshallSamlXml(response);

        return Base64Support.encode(marshalledXml.getBytes("UTF-8"), Base64Support.UNCHUNKED);

    } catch (MarshallingException | SignatureException | UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}
 
Example #3
Source File: SamlClient.java    From saml-client with MIT License 5 votes vote down vote up
/** Sign a SamlObject with default settings.
 * Note that this method is a no-op if spCredential is unset.
 * @param samlObject The object to sign
 *
 * @throws SamlException if {@link SignatureSupport#signObject(SignableXMLObject, SignatureSigningParameters) signObject} fails
 * */
private void signSAMLObject(SignableSAMLObject samlObject) throws SamlException {
  if (spCredential != null) {
    try {
      // Describe how we're going to sign the request
      SignatureBuilder signer = new SignatureBuilder();
      Signature signature = signer.buildObject(Signature.DEFAULT_ELEMENT_NAME);
      signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
      signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256);
      signature.setKeyInfo(
          new X509KeyInfoGeneratorFactory().newInstance().generate(spCredential));
      signature.setSigningCredential(spCredential);
      samlObject.setSignature(signature);

      // Actually sign the request
      SignatureSigningParameters signingParameters = new SignatureSigningParameters();
      signingParameters.setSigningCredential(spCredential);
      signingParameters.setSignatureCanonicalizationAlgorithm(
          SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
      signingParameters.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256);
      signingParameters.setKeyInfoGenerator(new X509KeyInfoGeneratorFactory().newInstance());
      SignatureSupport.signObject(samlObject, signingParameters);
    } catch (SecurityException | MarshallingException | SignatureException e) {
      throw new SamlException("Failed to sign request", e);
    }
  }
}
 
Example #4
Source File: Main.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Configures an identity provider with <a href="https://idp.ssocircle.com/meta-idp.xml">
 * the metadata of the SSOCircle</a>. You must <a href="https://idp.ssocircle.com/sso/hos/SPMetaInter.jsp">
 * register</a> this service provider, which we are configuring here, to the SSOCircle.
 * You can get the metadata of this service provider from {@code https://localhost:8443/saml/metadata}
 * after starting this server.
 *
 * <p>The {@code signing} and {@code encryption} key pair in the keystore {@code sample.jks} can be
 * generated with the following commands:
 * <pre>{@code
 * $ keytool -genkeypair -keystore sample.jks -storepass 'N5^X[hvG' -keyalg rsa -sigalg sha1withrsa \
 *     -dname 'CN=Unknown, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown' -alias signing
 *
 * $ keytool -genkeypair -keystore sample.jks -storepass 'N5^X[hvG' -keyalg rsa -sigalg sha1withrsa \
 *     -dname 'CN=Unknown, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown' -alias encryption
 * }</pre>
 *
 * <p>The certificate of the SSOCircle can be imported into the keystore with the following command.
 * You can specify its alias as same as its entity ID so that you do not need to specify the alias
 * when building a {@link SamlServiceProvider}. You can make {@code ssocircle.crt} file with
 * the certificate from <a href="https://www.ssocircle.com/en/idp-tips-tricks/public-idp-configuration/">
 * Public IDP Configuration</a> of SSOCircle.
 * <pre>{@code
 * $ keytool -importcert -keystore sample.jks -storepass 'N5^X[hvG' -file ssocircle.crt \
 *     -alias 'https://idp.ssocircle.com'
 * }</pre>
 */
private static SamlServiceProvider samlServiceProvider() throws IOException, GeneralSecurityException {
    final MyAuthHandler authHandler = new MyAuthHandler();

    // Specify information about your keystore.
    // The keystore contains two key pairs, which are identified as 'signing' and 'encryption'.
    final CredentialResolver credentialResolver =
            new KeyStoreCredentialResolverBuilder(Main.class.getClassLoader(), "sample.jks")
                    .type("PKCS12")
                    .password("N5^X[hvG")
                    // You need to specify your key pair and its password here.
                    .addKeyPassword("signing", "N5^X[hvG")
                    .addKeyPassword("encryption", "N5^X[hvG")
                    .build();

    return SamlServiceProvider.builder()
                              .credentialResolver(credentialResolver)
                              // Specify the entity ID of this service provider.
                              // You can specify what you want.
                              .entityId("armeria-sp")
                              .hostname("localhost")
                              // Specify an authorizer in order to authenticate a request.
                              .authorizer(authHandler)
                              // Speicify an SAML single sign-on handler
                              // which sends a response to an end user
                              // after he or she is authenticated or not.
                              .ssoHandler(authHandler)
                              // Specify the signature algorithm of your key.
                              .signatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA)
                              // The following information is from
                              // https://idp.ssocircle.com/meta-idp.xml.
                              .idp()
                              // Specify the entity ID of the identity provider.
                              // It can be found from the metadata of the identity provider.
                              .entityId("https://idp.ssocircle.com")
                              // Specify the endpoint that is supposed to send an authentication request.
                              .ssoEndpoint(ofHttpPost("https://idp.ssocircle.com:443/sso/SSOPOST/metaAlias/publicidp"))
                              .and()
                              .build();
}
 
Example #5
Source File: SAML2ITCase.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Test
public void spMetadata() {
    assumeTrue(SAML2SPDetector.isSAML2SPAvailable());

    try {
        SAML2SPService service = anonymous.getService(SAML2SPService.class);
        WebClient.client(service).accept(MediaType.APPLICATION_XML_TYPE);
        Response response = service.getMetadata(ADDRESS, "saml2sp");
        assertNotNull(response);

        Document responseDoc = StaxUtils.read(
                new InputStreamReader((InputStream) response.getEntity(), StandardCharsets.UTF_8));
        assertEquals("EntityDescriptor", responseDoc.getDocumentElement().getLocalName());
        assertEquals("urn:oasis:names:tc:SAML:2.0:metadata", responseDoc.getDocumentElement().getNamespaceURI());

        // Get the signature
        QName signatureQName = new QName(SignatureConstants.XMLSIG_NS, "Signature");
        Element signatureElement =
                DOMUtils.getFirstChildWithName(responseDoc.getDocumentElement(), signatureQName);
        assertNotNull(signatureElement);

        // Validate the signature
        XMLSignature signature = new XMLSignature(signatureElement, null);
        KeyStore keystore = KeyStore.getInstance("JKS");
        keystore.load(Loader.getResourceAsStream("keystore"), "changeit".toCharArray());
        assertTrue(signature.checkSignatureValue((X509Certificate) keystore.getCertificate("sp")));
    } catch (Exception e) {
        LOG.error("During SAML 2.0 SP metadata parsing", e);
        fail(e::getMessage);
    }
}
 
Example #6
Source File: SAML2ReaderWriter.java    From syncope with Apache License 2.0 5 votes vote down vote up
public void init() {
    X509KeyInfoGeneratorFactory keyInfoGeneratorFactory = new X509KeyInfoGeneratorFactory();
    keyInfoGeneratorFactory.setEmitEntityCertificate(true);
    keyInfoGenerator = keyInfoGeneratorFactory.newInstance();

    // Try to load a signature algorithm
    if (loader.getSignatureAlgorithm() != null) {
        SignatureAlgorithm loadedSignatureAlgorithm =
                SignatureAlgorithm.valueOf(loader.getSignatureAlgorithm());
        sigAlgo = loadedSignatureAlgorithm.getAlgorithm();
        jceSigAlgo = JCEMapper.translateURItoJCEID(sigAlgo);
        if (jceSigAlgo == null) {
            LOG.warn("Signature algorithm {} is not valid. Using default algorithm instead.",
                    loader.getSignatureAlgorithm());
            sigAlgo = null;
        }
    }

    if (sigAlgo == null) {
        sigAlgo = SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1;
        String pubKeyAlgo = loader.getCredential().getPublicKey().getAlgorithm();
        if (pubKeyAlgo.equalsIgnoreCase("DSA")) {
            sigAlgo = SignatureConstants.ALGO_ID_SIGNATURE_DSA_SHA1;
        } else if (pubKeyAlgo.equalsIgnoreCase("EC")) {
            sigAlgo = SignatureConstants.ALGO_ID_SIGNATURE_ECDSA_SHA1;
        }
        jceSigAlgo = JCEMapper.translateURItoJCEID(sigAlgo);
    }

    callbackHandler = new SAMLSPCallbackHandler(loader.getKeyPass());
}
 
Example #7
Source File: SAML2ReaderWriter.java    From syncope with Apache License 2.0 5 votes vote down vote up
public void sign(final SignableSAMLObject signableObject) throws SecurityException {
    org.opensaml.xmlsec.signature.Signature signature = OpenSAMLUtil.buildSignature();
    signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
    signature.setSignatureAlgorithm(sigAlgo);
    signature.setSigningCredential(loader.getCredential());
    signature.setKeyInfo(keyInfoGenerator.generate(loader.getCredential()));

    signableObject.setSignature(signature);
    signableObject.releaseDOM();
    signableObject.releaseChildrenDOM(true);
}
 
Example #8
Source File: LogoutRequestBuilder.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Build the logout request
 * @param subject name of the user
 * @param reason reason for generating logout request.
 * @return LogoutRequest object
 */
public LogoutRequest buildSignedLogoutRequest(String subject,String sessionIndexId, String reason,
        String issuerId, int tenantId, String tenantDomain, String destination, String nameIdFormat)
        throws SSOHostObjectException {
    Util.doBootstrap();
    LogoutRequest logoutReq = new org.opensaml.saml.saml2.core.impl.LogoutRequestBuilder().buildObject();
    logoutReq.setID(Util.createID());

    DateTime issueInstant = new DateTime();
    logoutReq.setIssueInstant(issueInstant);
    logoutReq.setNotOnOrAfter(new DateTime(issueInstant.getMillis() + 5 * 60 * 1000));

    IssuerBuilder issuerBuilder = new IssuerBuilder();
    Issuer issuer = issuerBuilder.buildObject();
    issuer.setValue(issuerId);
    logoutReq.setIssuer(issuer);

    logoutReq.setNameID(Util.buildNameID(nameIdFormat, subject));

    SessionIndex sessionIndex = new SessionIndexBuilder().buildObject();
    sessionIndex.setSessionIndex(sessionIndexId);
    logoutReq.getSessionIndexes().add(sessionIndex);

    logoutReq.setReason(reason);
    logoutReq.setDestination(destination);

    SSOAgentCarbonX509Credential ssoAgentCarbonX509Credential =
            new SSOAgentCarbonX509Credential(tenantId, tenantDomain);
    setSignature(logoutReq, SignatureConstants.ALGO_ID_SIGNATURE_RSA,
            new X509CredentialImpl(ssoAgentCarbonX509Credential));

    return logoutReq;
}
 
Example #9
Source File: LogoutRequestBuilder.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Overload Logout request for sessionIndexId is not exist case
 *
 * @param subject Subject
 * @param reason Reason for logout
 * @param issuerId id of issuer
 * @return Signed SAML logout request
 */
public LogoutRequest buildSignedLogoutRequest(String subject, String reason,
        String issuerId, int tenantId, String tenantDomain, String destination, String nameIdFormat)
        throws SSOHostObjectException {
    Util.doBootstrap();
    LogoutRequest logoutReq = new org.opensaml.saml.saml2.core.impl.LogoutRequestBuilder().buildObject();
    logoutReq.setID(Util.createID());

    DateTime issueInstant = new DateTime();
    logoutReq.setIssueInstant(issueInstant);
    logoutReq.setNotOnOrAfter(new DateTime(issueInstant.getMillis() + 5 * 60 * 1000));

    IssuerBuilder issuerBuilder = new IssuerBuilder();
    Issuer issuer = issuerBuilder.buildObject();
    issuer.setValue(issuerId);
    logoutReq.setIssuer(issuer);

    logoutReq.setNameID(Util.buildNameID(nameIdFormat, subject));

    logoutReq.setReason(reason);
    logoutReq.setDestination(destination);

    SSOAgentCarbonX509Credential ssoAgentCarbonX509Credential =
            new SSOAgentCarbonX509Credential(tenantId, tenantDomain);
    setSignature(logoutReq, SignatureConstants.ALGO_ID_SIGNATURE_RSA,
            new X509CredentialImpl(ssoAgentCarbonX509Credential));

    return logoutReq;
}
 
Example #10
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 #11
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 #12
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 #13
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);
}