Java Code Examples for org.apache.wss4j.common.crypto.Crypto#getDefaultX509Identifier()

The following examples show how to use org.apache.wss4j.common.crypto.Crypto#getDefaultX509Identifier() . 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: SimpleBatchSTSClient.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected X509Certificate getCert(Crypto crypto) throws Exception {
    String alias = (String)getProperty(SecurityConstants.STS_TOKEN_USERNAME);
    if (alias == null) {
        alias = crypto.getDefaultX509Identifier();
    }
    if (alias == null) {
        throw new Fault("No alias specified for retrieving PublicKey", LOG);
    }
    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias(alias);

    X509Certificate[] certs = crypto.getX509Certificates(cryptoType);
    if (certs == null || certs.length == 0) {
        throw new Fault("Could not get X509Certificate for alias " + alias, LOG);
    }
    return certs[0];
}
 
Example 2
Source File: AbstractSTSClient.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected X509Certificate getCert(Crypto crypto) throws Exception {
    if (crypto == null) {
        throw new Fault("No Crypto token properties are available to retrieve a certificate",
                        LOG);
    }

    String alias = (String)getProperty(SecurityConstants.STS_TOKEN_USERNAME);
    if (alias == null) {
        alias = crypto.getDefaultX509Identifier();
    }
    if (alias == null) {
        throw new Fault("No alias specified for retrieving PublicKey", LOG);
    }
    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias(alias);

    X509Certificate[] certs = crypto.getX509Certificates(cryptoType);
    if (certs == null || certs.length == 0) {
        throw new Fault("Could not get X509Certificate for alias " + alias, LOG);
    }
    return certs[0];
}
 
Example 3
Source File: CertsUtils.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
/**
 * Load an X.509 Certificate from a WSS4J Crypto instance using a keystore alias
 */
public static X509Certificate getX509CertificateFromCrypto(Crypto crypto, String keyAlias)
    throws WSSecurityException {
    if (keyAlias == null || "".equals(keyAlias)) {
        keyAlias = crypto.getDefaultX509Identifier();
    }

    if (keyAlias == null) {
        throw new RuntimeException("No keystore alias was specified to sign the metadata");
    }

    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias(keyAlias);
    X509Certificate[] issuerCerts = crypto.getX509Certificates(cryptoType);
    if (issuerCerts == null || issuerCerts.length == 0) {
        throw new RuntimeException(
                "No issuer certs were found to sign the metadata using issuer name: "
                        + keyAlias);
    }
    return issuerCerts[0];
}
 
Example 4
Source File: AbstractBindingBuilder.java    From cxf with Apache License 2.0 5 votes vote down vote up
public Crypto getEncryptionCrypto() throws WSSecurityException {
    Crypto crypto =
        getCrypto(SecurityConstants.ENCRYPT_CRYPTO, SecurityConstants.ENCRYPT_PROPERTIES);
    boolean enableRevocation = false;
    String enableRevStr =
        (String)SecurityUtils.getSecurityPropertyValue(SecurityConstants.ENABLE_REVOCATION, message);
    if (enableRevStr != null) {
        enableRevocation = Boolean.parseBoolean(enableRevStr);
    }
    if (enableRevocation && crypto != null) {
        CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
        String encrUser =
            (String)SecurityUtils.getSecurityPropertyValue(SecurityConstants.ENCRYPT_USERNAME, message);
        if (encrUser == null) {
            try {
                encrUser = crypto.getDefaultX509Identifier();
            } catch (WSSecurityException e1) {
                throw new Fault(e1);
            }
        }
        cryptoType.setAlias(encrUser);
        X509Certificate[] certs = crypto.getX509Certificates(cryptoType);
        if (certs != null && certs.length > 0) {
            crypto.verifyTrust(certs, enableRevocation, null, null);
        }
    }
    if (crypto != null) {
        this.message.getExchange().put(SecurityConstants.ENCRYPT_CRYPTO, crypto);
    }
    return crypto;

}
 
Example 5
Source File: XmlSecInInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void configureDecryptionKeys(Message message, XMLSecurityProperties properties)
    throws IOException,
    UnsupportedCallbackException, WSSecurityException {
    String cryptoKey = null;
    String propKey = null;
    if (RSSecurityUtils.isSignedAndEncryptedTwoWay(message)) {
        cryptoKey = SecurityConstants.SIGNATURE_CRYPTO;
        propKey = SecurityConstants.SIGNATURE_PROPERTIES;
    } else {
        cryptoKey = SecurityConstants.ENCRYPT_CRYPTO;
        propKey = SecurityConstants.ENCRYPT_PROPERTIES;
    }

    Crypto crypto = null;
    try {
        crypto = new CryptoLoader().getCrypto(message, cryptoKey, propKey);
    } catch (Exception ex) {
        throwFault("Crypto can not be loaded", ex);
    }

    if (crypto != null) {
        String alias = decryptionAlias;
        if (alias == null) {
            alias = crypto.getDefaultX509Identifier();
        }
        if (alias != null) {
            CallbackHandler callback = RSSecurityUtils.getCallbackHandler(message, this.getClass());
            WSPasswordCallback passwordCallback =
                new WSPasswordCallback(alias, WSPasswordCallback.DECRYPT);
            callback.handle(new Callback[] {passwordCallback});

            Key privateKey = crypto.getPrivateKey(alias, passwordCallback.getPassword());
            properties.setDecryptionKey(privateKey);
        }
    }
}
 
Example 6
Source File: RSSecurityUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static String getUserName(Crypto crypto, String userName) {
    if (crypto != null && StringUtils.isEmpty(userName)) {
        try {
            userName = crypto.getDefaultX509Identifier();
        } catch (WSSecurityException e1) {
            throw new Fault(e1);
        }
    }
    return userName;
}
 
Example 7
Source File: AbstractBindingBuilder.java    From cxf with Apache License 2.0 4 votes vote down vote up
public String setEncryptionUser(WSSecEncryptedKey encrKeyBuilder, AbstractToken token,
                              boolean sign, Crypto crypto) {
    // Check for prepared certificate property
    X509Certificate encrCert =
        (X509Certificate)SecurityUtils.getSecurityPropertyValue(SecurityConstants.ENCRYPT_CERT, message);
    if (encrCert != null) {
        encrKeyBuilder.setUseThisCert(encrCert);
        return null;
    }

    String key = sign ? SecurityConstants.SIGNATURE_USERNAME : SecurityConstants.ENCRYPT_USERNAME;
    String encrUser = (String)SecurityUtils.getSecurityPropertyValue(key, message);

    if (crypto != null && (encrUser == null || "".equals(encrUser))) {
        try {
            encrUser = crypto.getDefaultX509Identifier();
        } catch (WSSecurityException e1) {
            throw new Fault(e1);
        }
    }
    if (encrUser == null || "".equals(encrUser)) {
        unassertPolicy(token, "A " + (sign ? "signature" : "encryption") + " username needs to be declared.");
    }
    if (ConfigurationConstants.USE_REQ_SIG_CERT.equals(encrUser)) {
        List<WSHandlerResult> results =
            CastUtils.cast((List<?>)
                message.getExchange().getInMessage().get(WSHandlerConstants.RECV_RESULTS));
        if (results != null) {
            encrKeyBuilder.setUseThisCert(WSS4JUtils.getReqSigCert(results));

            //TODO This is a hack, this should not come under USE_REQ_SIG_CERT
            if (encrKeyBuilder.isCertSet()) {
                encrKeyBuilder.setUserInfo(getUsername(results));
            }
        } else {
            unassertPolicy(token, "No security results in incoming message");
        }
    } else {
        encrKeyBuilder.setUserInfo(encrUser);
    }

    return encrUser;
}
 
Example 8
Source File: TrustedIdpSAMLProtocolHandler.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
/**
 * Sign a request according to the redirect binding spec for Web SSO
 */
private void signRequest(
    String authnRequest,
    String relayState,
    Idp config,
    UriBuilder ub
) throws Exception {
    Crypto crypto = CertsUtils.getCryptoFromCertificate(config.getCertificate());
    if (crypto == null) {
        LOG.error("No crypto instance of properties file configured for signature");
        throw new IllegalStateException("Invalid IdP configuration");
    }

    String alias = crypto.getDefaultX509Identifier();
    X509Certificate cert = CertsUtils.getX509CertificateFromCrypto(crypto, alias);
    if (cert == null) {
        LOG.error("No cert was found to sign the request using alias: " + alias);
        throw new IllegalStateException("Invalid IdP configuration");
    }

    String sigAlgo = SSOConstants.RSA_SHA1;
    String pubKeyAlgo = cert.getPublicKey().getAlgorithm();
    String jceSigAlgo = "SHA1withRSA";
    LOG.debug("automatic sig algo detection: " + pubKeyAlgo);
    if ("DSA".equalsIgnoreCase(pubKeyAlgo)) {
        sigAlgo = SSOConstants.DSA_SHA1;
        jceSigAlgo = "SHA1withDSA";
    }
    LOG.debug("Using Signature algorithm " + sigAlgo);

    ub.queryParam(SSOConstants.SIG_ALG, URLEncoder.encode(sigAlgo, "UTF-8"));

    // Get the password
    String password = config.getCertificatePassword();

    // Get the private key
    PrivateKey privateKey = crypto.getPrivateKey(alias, password);

    // Sign the request
    Signature signature = Signature.getInstance(jceSigAlgo);
    signature.initSign(privateKey);

    String requestToSign =
        SSOConstants.SAML_REQUEST + "=" + authnRequest + "&"
        + SSOConstants.RELAY_STATE + "=" + relayState + "&"
        + SSOConstants.SIG_ALG + "=" + URLEncoder.encode(sigAlgo, "UTF-8");

    signature.update(requestToSign.getBytes(StandardCharsets.UTF_8));
    byte[] signBytes = signature.sign();

    String encodedSignature = Base64.getEncoder().encodeToString(signBytes);

    ub.queryParam(SSOConstants.SIGNATURE, URLEncoder.encode(encodedSignature, "UTF-8"));
}
 
Example 9
Source File: IdpMetadataWriter.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
private void writeFederationMetadata(
    XMLStreamWriter writer, Idp config, Crypto crypto
) throws XMLStreamException {

    writer.writeNamespace("fed", WS_FEDERATION_NS);
    writer.writeNamespace("wsa", WS_ADDRESSING_NS);
    writer.writeNamespace("auth", WS_FEDERATION_NS);

    writer.writeStartElement("md", "RoleDescriptor", WS_FEDERATION_NS);
    writer.writeAttribute(SCHEMA_INSTANCE_NS, "type", "fed:SecurityTokenServiceType");
    writer.writeAttribute("protocolSupportEnumeration", WS_FEDERATION_NS);
    if (config.getServiceDescription() != null && config.getServiceDescription().length() > 0) {
        writer.writeAttribute("ServiceDescription", config.getServiceDescription());
    }
    if (config.getServiceDisplayName() != null && config.getServiceDisplayName().length() > 0) {
        writer.writeAttribute("ServiceDisplayName", config.getServiceDisplayName());
    }

    //http://docs.oasis-open.org/security/saml/v2.0/saml-schema-metadata-2.0.xsd
    //missing organization, contactperson

    //KeyDescriptor
    writer.writeStartElement("md", "KeyDescriptor", SAML2_METADATA_NS);
    writer.writeAttribute("use", "signing");
    writer.writeStartElement("ds", "KeyInfo", "http://www.w3.org/2000/09/xmldsig#");
    writer.writeNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");
    writer.writeStartElement("ds", "X509Data", "http://www.w3.org/2000/09/xmldsig#");
    writer.writeStartElement("ds", "X509Certificate", "http://www.w3.org/2000/09/xmldsig#");

    try {
        String keyAlias = crypto.getDefaultX509Identifier();
        X509Certificate cert = CertsUtils.getX509CertificateFromCrypto(crypto, keyAlias);
        writer.writeCharacters(Base64.getEncoder().encodeToString(cert.getEncoded()));
    } catch (Exception ex) {
        LOG.error("Failed to add certificate information to metadata. Metadata incomplete", ex);
    }

    writer.writeEndElement(); // X509Certificate
    writer.writeEndElement(); // X509Data
    writer.writeEndElement(); // KeyInfo
    writer.writeEndElement(); // KeyDescriptor


    // SecurityTokenServiceEndpoint
    writer.writeStartElement("fed", "SecurityTokenServiceEndpoint", WS_FEDERATION_NS);
    writer.writeStartElement("wsa", "EndpointReference", WS_ADDRESSING_NS);

    writer.writeStartElement("wsa", "Address", WS_ADDRESSING_NS);
    writer.writeCharacters(config.getStsUrl().toString());

    writer.writeEndElement(); // Address
    writer.writeEndElement(); // EndpointReference
    writer.writeEndElement(); // SecurityTokenServiceEndpoint


    // PassiveRequestorEndpoint
    writer.writeStartElement("fed", "PassiveRequestorEndpoint", WS_FEDERATION_NS);
    writer.writeStartElement("wsa", "EndpointReference", WS_ADDRESSING_NS);

    writer.writeStartElement("wsa", "Address", WS_ADDRESSING_NS);
    writer.writeCharacters(config.getIdpUrl().toString());

    writer.writeEndElement(); // Address
    writer.writeEndElement(); // EndpointReference
    writer.writeEndElement(); // PassiveRequestorEndpoint


    // create ClaimsType section
    if (config.getClaimTypesOffered() != null && !config.getClaimTypesOffered().isEmpty()) {
        writer.writeStartElement("fed", "ClaimTypesOffered", WS_FEDERATION_NS);
        for (Claim claim : config.getClaimTypesOffered()) {

            writer.writeStartElement("auth", "ClaimType", WS_FEDERATION_NS);
            writer.writeAttribute("Uri", claim.getClaimType().toString());
            writer.writeAttribute("Optional", "true");
            writer.writeEndElement(); // ClaimType

        }
        writer.writeEndElement(); // ClaimTypesOffered
    }

    writer.writeEndElement(); // RoleDescriptor
}
 
Example 10
Source File: IdpMetadataWriter.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
private void writeSAMLSSOMetadata(
    XMLStreamWriter writer, Idp config, Crypto crypto
) throws XMLStreamException {

    writer.writeStartElement("md", "IDPSSODescriptor", SAML2_METADATA_NS);
    writer.writeAttribute("WantAuthnRequestsSigned", "true");
    writer.writeAttribute("protocolSupportEnumeration", "urn:oasis:names:tc:SAML:2.0:protocol");

    //KeyDescriptor
    writer.writeStartElement("md", "KeyDescriptor", SAML2_METADATA_NS);
    writer.writeAttribute("use", "signing");
    writer.writeStartElement("ds", "KeyInfo", "http://www.w3.org/2000/09/xmldsig#");
    writer.writeNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");
    writer.writeStartElement("ds", "X509Data", "http://www.w3.org/2000/09/xmldsig#");
    writer.writeStartElement("ds", "X509Certificate", "http://www.w3.org/2000/09/xmldsig#");

    try {
        String keyAlias = crypto.getDefaultX509Identifier();
        X509Certificate cert = CertsUtils.getX509CertificateFromCrypto(crypto, keyAlias);
        writer.writeCharacters(Base64.getEncoder().encodeToString(cert.getEncoded()));
    } catch (Exception ex) {
        LOG.error("Failed to add certificate information to metadata. Metadata incomplete", ex);
    }

    writer.writeEndElement(); // X509Certificate
    writer.writeEndElement(); // X509Data
    writer.writeEndElement(); // KeyInfo
    writer.writeEndElement(); // KeyDescriptor


    writer.writeStartElement("md", "NameIDFormat", SAML2_METADATA_NS);
    writer.writeCharacters("urn:oasis:names:tc:SAML:2.0:nameid-format:persistent");
    writer.writeEndElement(); // NameIDFormat

    writer.writeStartElement("md", "NameIDFormat", SAML2_METADATA_NS);
    writer.writeCharacters("urn:oasis:names:tc:SAML:2.0:nameid-format:unspecified");
    writer.writeEndElement(); // NameIDFormat

    writer.writeStartElement("md", "NameIDFormat", SAML2_METADATA_NS);
    writer.writeCharacters("urn:oasis:names:tc:SAML:2.0:nameid-format:emailAddress");
    writer.writeEndElement(); // NameIDFormat

    // SingleSignOnService
    writer.writeStartElement("md", "SingleSignOnService", SAML2_METADATA_NS);
    writer.writeAttribute("Binding", "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect");
    writer.writeAttribute("Location", config.getIdpUrl().toString());
    writer.writeEndElement(); // SingleSignOnService

    // SingleSignOnService
    writer.writeStartElement("md", "SingleSignOnService", SAML2_METADATA_NS);
    writer.writeAttribute("Binding", "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST");
    writer.writeAttribute("Location", config.getIdpUrl().toString());
    writer.writeEndElement(); // SingleSignOnService

    writer.writeEndElement(); // IDPSSODescriptor
}
 
Example 11
Source File: ServiceMetadataWriter.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
private void writeSAMLMetadata(
    XMLStreamWriter writer,
    TrustedIdp config,
    String serviceURL,
    Crypto crypto
) throws Exception {

    writer.writeStartElement("md", "SPSSODescriptor", SAML2_METADATA_NS);
    boolean signRequest =
        isPropertyConfigured(config, TrustedIdpSAMLProtocolHandler.SIGN_REQUEST, true);
    writer.writeAttribute("AuthnRequestsSigned", Boolean.toString(signRequest));
    writer.writeAttribute("WantAssertionsSigned", "true");
    writer.writeAttribute("protocolSupportEnumeration", "urn:oasis:names:tc:SAML:2.0:protocol");

    writer.writeStartElement("md", "AssertionConsumerService", SAML2_METADATA_NS);
    writer.writeAttribute("Location", serviceURL);
    writer.writeAttribute("index", "0");
    writer.writeAttribute("isDefault", "true");
    writer.writeAttribute("Binding", "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST");
    writer.writeEndElement(); // AssertionConsumerService

    if (signRequest) {
        writer.writeStartElement("md", "KeyDescriptor", SAML2_METADATA_NS);
        writer.writeAttribute("use", "signing");

        writer.writeStartElement("ds", "KeyInfo", "http://www.w3.org/2000/09/xmldsig#");
        writer.writeNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");
        writer.writeStartElement("ds", "X509Data", "http://www.w3.org/2000/09/xmldsig#");
        writer.writeStartElement("ds", "X509Certificate", "http://www.w3.org/2000/09/xmldsig#");

        // Write the Base-64 encoded certificate

        String keyAlias = crypto.getDefaultX509Identifier();
        X509Certificate cert = CertsUtils.getX509CertificateFromCrypto(crypto, keyAlias);

        if (cert == null) {
            throw new ProcessingException(
                "No signing certs were found to insert into the metadata using name: "
                    + keyAlias);
        }
        byte[] data = cert.getEncoded();
        String encodedCertificate = Base64.getEncoder().encodeToString(data);
        writer.writeCharacters(encodedCertificate);

        writer.writeEndElement(); // X509Certificate
        writer.writeEndElement(); // X509Data
        writer.writeEndElement(); // KeyInfo
        writer.writeEndElement(); // KeyDescriptor
    }

    writer.writeEndElement(); // SPSSODescriptor
}