org.opensaml.xmlsec.keyinfo.impl.X509KeyInfoGeneratorFactory Java Examples

The following examples show how to use org.opensaml.xmlsec.keyinfo.impl.X509KeyInfoGeneratorFactory. 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: 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 #2
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 #3
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 #4
Source File: MockSamlIdpServer.java    From deprecated-security-advanced-modules with Apache License 2.0 4 votes vote down vote up
private String createMetadata() {
    try {
        EntityDescriptor idpEntityDescriptor = createSamlElement(EntityDescriptor.class);
        idpEntityDescriptor.setEntityID(idpEntityId);

        IDPSSODescriptor idpSsoDescriptor = createSamlElement(IDPSSODescriptor.class);
        idpEntityDescriptor.getRoleDescriptors().add(idpSsoDescriptor);

        idpSsoDescriptor.setWantAuthnRequestsSigned(wantAuthnRequestsSigned);
        idpSsoDescriptor.addSupportedProtocol(SAMLConstants.SAML20P_NS);

        SingleLogoutService redirectSingleLogoutService = createSamlElement(SingleLogoutService.class);
        idpSsoDescriptor.getSingleLogoutServices().add(redirectSingleLogoutService);

        redirectSingleLogoutService.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect");
        redirectSingleLogoutService.setLocation(getSamlSloUri());

        idpSsoDescriptor.getNameIDFormats()
                .add(createNameIDFormat("urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified"));

        SingleSignOnService redirectSingleSignOnService = createSamlElement(SingleSignOnService.class);
        idpSsoDescriptor.getSingleSignOnServices().add(redirectSingleSignOnService);

        redirectSingleSignOnService.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect");
        redirectSingleSignOnService.setLocation(getSamlSsoUri());

        X509KeyInfoGeneratorFactory keyInfoGeneratorFactory = new X509KeyInfoGeneratorFactory();
        keyInfoGeneratorFactory.setEmitEntityCertificate(true);
        KeyInfoGenerator keyInfoGenerator = keyInfoGeneratorFactory.newInstance();

        KeyDescriptor signingKeyDescriptor = createSamlElement(KeyDescriptor.class);
        idpSsoDescriptor.getKeyDescriptors().add(signingKeyDescriptor);

        signingKeyDescriptor.setUse(UsageType.SIGNING);

        signingKeyDescriptor
                .setKeyInfo(keyInfoGenerator.generate(new BasicX509Credential(this.signingCertificate)));

        return marshallSamlXml(idpEntityDescriptor);
    } catch (org.opensaml.security.SecurityException e) {
        throw new RuntimeException(e);
    }
}
 
Example #5
Source File: SamlMetadataServiceFunction.java    From armeria with Apache License 2.0 4 votes vote down vote up
private EntityDescriptor buildMetadataEntityDescriptorElement(
        String defaultHostname, SamlPortConfig portConfig) {
    final EntityDescriptor entityDescriptor = build(EntityDescriptor.DEFAULT_ELEMENT_NAME);
    entityDescriptor.setEntityID(entityId);

    final SPSSODescriptor spSsoDescriptor = build(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
    spSsoDescriptor.setAuthnRequestsSigned(true);
    spSsoDescriptor.setWantAssertionsSigned(true);
    spSsoDescriptor.addSupportedProtocol(SAMLConstants.SAML20P_NS);

    final List<String> nameIdFormats = idpConfigs.values().stream()
                                                 .map(p -> p.nameIdPolicy().format())
                                                 .distinct()
                                                 .map(SamlNameIdFormat::urn)
                                                 .collect(Collectors.toList());
    spSsoDescriptor.getNameIDFormats().addAll(buildNameIdFormatElements(nameIdFormats));

    final List<SingleLogoutService> sloList = spSsoDescriptor.getSingleLogoutServices();
    singleLogoutEndpoints.forEach(endpoint -> {
        final SingleLogoutService slo = build(SingleLogoutService.DEFAULT_ELEMENT_NAME);
        slo.setBinding(endpoint.bindingProtocol().urn());
        slo.setLocation(endpoint.toUriString(portConfig.scheme().uriText(),
                                             defaultHostname,
                                             portConfig.port()));
        sloList.add(slo);
    });

    int acsIndex = 0;
    final List<AssertionConsumerService> services = spSsoDescriptor.getAssertionConsumerServices();
    for (final SamlAssertionConsumerConfig acs : assertionConsumerConfigs) {
        services.add(buildAssertionConsumerServiceElement(acs, portConfig, defaultHostname, acsIndex++));
    }

    final X509KeyInfoGeneratorFactory keyInfoGeneratorFactory = new X509KeyInfoGeneratorFactory();
    keyInfoGeneratorFactory.setEmitEntityCertificate(true);
    keyInfoGeneratorFactory.setEmitEntityCertificateChain(true);
    final KeyInfoGenerator keyInfoGenerator = keyInfoGeneratorFactory.newInstance();

    try {
        spSsoDescriptor.getKeyDescriptors().add(
                buildKeyDescriptorElement(UsageType.SIGNING,
                                          keyInfoGenerator.generate(signingCredential)));
        spSsoDescriptor.getKeyDescriptors().add(
                buildKeyDescriptorElement(UsageType.ENCRYPTION,
                                          keyInfoGenerator.generate(encryptionCredential)));
    } catch (SecurityException e) {
        throw new SamlException("failed to generate KeyInfo element", e);
    }

    entityDescriptor.getRoleDescriptors().add(spSsoDescriptor);
    return entityDescriptor;
}
 
Example #6
Source File: SAML2SPLogic.java    From syncope with Apache License 2.0 4 votes vote down vote up
@PreAuthorize("isAuthenticated()")
public void getMetadata(final String spEntityID, final String urlContext, final OutputStream os) {
    check();

    try {
        EntityDescriptor spEntityDescriptor = new EntityDescriptorBuilder().buildObject();
        spEntityDescriptor.setEntityID(spEntityID);

        SPSSODescriptor spSSODescriptor = new SPSSODescriptorBuilder().buildObject();
        spSSODescriptor.setWantAssertionsSigned(true);
        spSSODescriptor.setAuthnRequestsSigned(true);
        spSSODescriptor.addSupportedProtocol(SAMLConstants.SAML20P_NS);

        X509KeyInfoGeneratorFactory keyInfoGeneratorFactory = new X509KeyInfoGeneratorFactory();
        keyInfoGeneratorFactory.setEmitEntityCertificate(true);
        KeyInfoGenerator keyInfoGenerator = keyInfoGeneratorFactory.newInstance();
        keyInfoGenerator.generate(loader.getCredential());

        KeyDescriptor keyDescriptor = new KeyDescriptorBuilder().buildObject();
        keyDescriptor.setKeyInfo(keyInfoGenerator.generate(loader.getCredential()));
        spSSODescriptor.getKeyDescriptors().add(keyDescriptor);

        NameIDFormat nameIDFormat = new NameIDFormatBuilder().buildObject();
        nameIDFormat.setFormat(NameIDType.PERSISTENT);
        spSSODescriptor.getNameIDFormats().add(nameIDFormat);
        nameIDFormat = new NameIDFormatBuilder().buildObject();
        nameIDFormat.setFormat(NameIDType.TRANSIENT);
        spSSODescriptor.getNameIDFormats().add(nameIDFormat);

        for (SAML2BindingType bindingType : SAML2BindingType.values()) {
            AssertionConsumerService assertionConsumerService = new AssertionConsumerServiceBuilder().buildObject();
            assertionConsumerService.setIndex(bindingType.ordinal());
            assertionConsumerService.setBinding(bindingType.getUri());
            assertionConsumerService.setLocation(getAssertionConsumerURL(spEntityID, urlContext));
            spSSODescriptor.getAssertionConsumerServices().add(assertionConsumerService);
            spEntityDescriptor.getRoleDescriptors().add(spSSODescriptor);

            String sloUrl = spEntityID + urlContext + "/logout";
            validateUrl(sloUrl);

            SingleLogoutService singleLogoutService = new SingleLogoutServiceBuilder().buildObject();
            singleLogoutService.setBinding(bindingType.getUri());
            singleLogoutService.setLocation(sloUrl);
            singleLogoutService.setResponseLocation(sloUrl);
            spSSODescriptor.getSingleLogoutServices().add(singleLogoutService);
        }

        spEntityDescriptor.getRoleDescriptors().add(spSSODescriptor);
        saml2rw.sign(spEntityDescriptor);

        SAML2ReaderWriter.write(new OutputStreamWriter(os), spEntityDescriptor, true);
    } catch (Exception e) {
        LOG.error("While getting SP metadata", e);
        SyncopeClientException sce = SyncopeClientException.build(ClientExceptionType.Unknown);
        sce.getElements().add(e.getMessage());
        throw sce;
    }
}
 
Example #7
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 #8
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 #9
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);
}