Search in sources :

Example 6 with XMLX509Certificate

use of org.apache.xml.security.keys.content.x509.XMLX509Certificate in project santuario-java by apache.

the class X509CertificateResolver method engineLookupResolveX509Certificate.

/**
 * Method engineResolveX509Certificate
 * {@inheritDoc}
 * @param element
 * @param baseURI
 * @param storage
 *
 * @throws KeyResolverException
 */
public X509Certificate engineLookupResolveX509Certificate(Element element, String baseURI, StorageResolver storage) throws KeyResolverException {
    try {
        Element[] els = XMLUtils.selectDsNodes(element.getFirstChild(), Constants._TAG_X509CERTIFICATE);
        if (els == null || els.length == 0) {
            Element el = XMLUtils.selectDsNode(element.getFirstChild(), Constants._TAG_X509DATA, 0);
            if (el != null) {
                return engineLookupResolveX509Certificate(el, baseURI, storage);
            }
            return null;
        }
        // populate Object array
        for (int i = 0; i < els.length; i++) {
            XMLX509Certificate xmlCert = new XMLX509Certificate(els[i], baseURI);
            X509Certificate cert = xmlCert.getX509Certificate();
            if (cert != null) {
                return cert;
            }
        }
        return null;
    } catch (XMLSecurityException ex) {
        LOG.debug("Security Exception", ex);
        throw new KeyResolverException(ex);
    }
}
Also used : XMLX509Certificate(org.apache.xml.security.keys.content.x509.XMLX509Certificate) Element(org.w3c.dom.Element) KeyResolverException(org.apache.xml.security.keys.keyresolver.KeyResolverException) X509Certificate(java.security.cert.X509Certificate) XMLX509Certificate(org.apache.xml.security.keys.content.x509.XMLX509Certificate) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException)

Example 7 with XMLX509Certificate

use of org.apache.xml.security.keys.content.x509.XMLX509Certificate in project jdk8u_jdk by JetBrains.

the class PrivateKeyResolver method resolveX509Certificate.

/*
     * Search for a private key entry in the KeyStore with the same Certificate.
     */
private PrivateKey resolveX509Certificate(XMLX509Certificate x509Cert) throws XMLSecurityException, KeyStoreException {
    log.log(java.util.logging.Level.FINE, "Can I resolve X509Certificate?");
    byte[] x509CertBytes = x509Cert.getCertificateBytes();
    Enumeration<String> aliases = keyStore.aliases();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        if (keyStore.isKeyEntry(alias)) {
            Certificate cert = keyStore.getCertificate(alias);
            if (cert instanceof X509Certificate) {
                byte[] certBytes = null;
                try {
                    certBytes = cert.getEncoded();
                } catch (CertificateEncodingException e1) {
                }
                if (certBytes != null && Arrays.equals(certBytes, x509CertBytes)) {
                    log.log(java.util.logging.Level.FINE, "match !!! ");
                    try {
                        Key key = keyStore.getKey(alias, password);
                        if (key instanceof PrivateKey) {
                            return (PrivateKey) key;
                        }
                    } catch (Exception e) {
                        log.log(java.util.logging.Level.FINE, "Cannot recover the key", e);
                    // Keep searching
                    }
                }
            }
        }
    }
    return null;
}
Also used : PrivateKey(java.security.PrivateKey) CertificateEncodingException(java.security.cert.CertificateEncodingException) X509Certificate(java.security.cert.X509Certificate) XMLX509Certificate(com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509Certificate) PublicKey(java.security.PublicKey) Key(java.security.Key) PrivateKey(java.security.PrivateKey) SecretKey(javax.crypto.SecretKey) KeyStoreException(java.security.KeyStoreException) KeyResolverException(com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException) XMLSecurityException(com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException) CertificateEncodingException(java.security.cert.CertificateEncodingException) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate) XMLX509Certificate(com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509Certificate)

Example 8 with XMLX509Certificate

use of org.apache.xml.security.keys.content.x509.XMLX509Certificate in project ddf by codice.

the class X509PathTokenValidator method validateToken.

/**
     * Validate a Token using the given TokenValidatorParameters.
     *
     * @param tokenParameters
     * @return TokenValidatorResponse
     */
public TokenValidatorResponse validateToken(TokenValidatorParameters tokenParameters) {
    LOGGER.trace("Validating X.509 Token");
    STSPropertiesMBean stsProperties = tokenParameters.getStsProperties();
    Crypto sigCrypto = stsProperties.getSignatureCrypto();
    CallbackHandler callbackHandler = stsProperties.getCallbackHandler();
    RequestData requestData = new RequestData();
    requestData.setSigVerCrypto(sigCrypto);
    requestData.setWssConfig(WSSConfig.getNewInstance());
    requestData.setCallbackHandler(callbackHandler);
    requestData.setMsgContext(tokenParameters.getMessageContext());
    requestData.setSubjectCertConstraints(certConstraints.getCompiledSubjectContraints());
    TokenValidatorResponse response = new TokenValidatorResponse();
    ReceivedToken validateTarget = tokenParameters.getToken();
    validateTarget.setState(STATE.INVALID);
    response.setToken(validateTarget);
    BinarySecurity binarySecurity = null;
    BinarySecurityTokenType binarySecurityType = null;
    if (validateTarget.isBinarySecurityToken()) {
        binarySecurityType = (BinarySecurityTokenType) validateTarget.getToken();
        // Test the encoding type
        String encodingType = binarySecurityType.getEncodingType();
        if (!BASE64_ENCODING.equals(encodingType)) {
            LOGGER.trace("Bad encoding type attribute specified: {}", encodingType);
            return response;
        }
        //
        // Turn the received JAXB object into a DOM element
        //
        Document doc = DOMUtils.createDocument();
        binarySecurity = new X509Security(doc);
        binarySecurity.setEncodingType(encodingType);
        binarySecurity.setValueType(binarySecurityType.getValueType());
        String data = binarySecurityType.getValue();
        Node textNode = doc.createTextNode(data);
        binarySecurity.getElement().appendChild(textNode);
    } else if (validateTarget.isDOMElement()) {
        try {
            Document doc = DOMUtils.createDocument();
            binarySecurity = new X509Security(doc);
            binarySecurity.setEncodingType(BASE64_ENCODING);
            X509Data x509Data = new X509Data((Element) validateTarget.getToken(), "");
            if (x509Data.containsCertificate()) {
                XMLX509Certificate xmlx509Certificate = x509Data.itemCertificate(0);
                if (xmlx509Certificate == null) {
                    throw new WSSecurityException(WSSecurityException.ErrorCode.INVALID_SECURITY_TOKEN);
                }
                X509Certificate cert = xmlx509Certificate.getX509Certificate();
                ((X509Security) binarySecurity).setX509Certificate(cert);
            }
        } catch (WSSecurityException ex) {
            LOGGER.debug("Unable to set certificate", ex);
            return response;
        } catch (XMLSecurityException ex) {
            LOGGER.debug("Unable to get certificates", ex);
            return response;
        }
    } else {
        return response;
    }
    //
    try {
        Credential credential = new Credential();
        credential.setBinarySecurityToken(binarySecurity);
        if (merlin != null) {
            byte[] token = binarySecurity.getToken();
            if (token != null) {
                if (binarySecurityType != null) {
                    if (binarySecurityType.getValueType().equals(X509_PKI_PATH)) {
                        X509Certificate[] certificates = merlin.getCertificatesFromBytes(token);
                        if (certificates != null) {
                            credential.setCertificates(certificates);
                        }
                    } else {
                        X509Certificate singleCert = merlin.loadCertificate(new ByteArrayInputStream(token));
                        credential.setCertificates(new X509Certificate[] { singleCert });
                    }
                }
            } else {
                LOGGER.debug("Binary Security Token bytes were null.");
            }
        }
        Credential returnedCredential = validator.validate(credential, requestData);
        X500Principal subjectX500Principal = returnedCredential.getCertificates()[0].getSubjectX500Principal();
        response.setPrincipal(subjectX500Principal);
        if (response.getAdditionalProperties() == null) {
            response.setAdditionalProperties(new HashMap<>());
        }
        try {
            String emailAddress = SubjectUtils.getEmailAddress(subjectX500Principal);
            if (emailAddress != null) {
                response.getAdditionalProperties().put(SubjectUtils.EMAIL_ADDRESS_CLAIM_URI, emailAddress);
            }
            String country = SubjectUtils.getCountry(subjectX500Principal);
            if (country != null) {
                response.getAdditionalProperties().put(SubjectUtils.COUNTRY_CLAIM_URI, country);
            }
        } catch (Exception e) {
            LOGGER.debug("Unable to set email address or country from certificate.", e);
        }
        validateTarget.setState(STATE.VALID);
        validateTarget.setPrincipal(subjectX500Principal);
    } catch (WSSecurityException ex) {
        LOGGER.debug("Unable to validate credentials.", ex);
    }
    return response;
}
Also used : CallbackHandler(javax.security.auth.callback.CallbackHandler) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) Document(org.w3c.dom.Document) X509Data(org.apache.xml.security.keys.content.X509Data) BinarySecurityTokenType(org.apache.cxf.ws.security.sts.provider.model.secext.BinarySecurityTokenType) RequestData(org.apache.wss4j.dom.handler.RequestData) ReceivedToken(org.apache.cxf.sts.request.ReceivedToken) X509Security(org.apache.wss4j.common.token.X509Security) Credential(org.apache.wss4j.dom.validate.Credential) BinarySecurity(org.apache.wss4j.common.token.BinarySecurity) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) X509Certificate(java.security.cert.X509Certificate) XMLX509Certificate(org.apache.xml.security.keys.content.x509.XMLX509Certificate) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) IOException(java.io.IOException) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException) XMLX509Certificate(org.apache.xml.security.keys.content.x509.XMLX509Certificate) Crypto(org.apache.wss4j.common.crypto.Crypto) STSPropertiesMBean(org.apache.cxf.sts.STSPropertiesMBean) ByteArrayInputStream(java.io.ByteArrayInputStream) X500Principal(javax.security.auth.x500.X500Principal) TokenValidatorResponse(org.apache.cxf.sts.token.validator.TokenValidatorResponse)

Example 9 with XMLX509Certificate

use of org.apache.xml.security.keys.content.x509.XMLX509Certificate in project santuario-java by apache.

the class XMLX509CertificateTest method testGetX509Certificate.

@org.junit.Test
public void testGetX509Certificate() throws Exception {
    File f = new File(BASEDIR + SEP + "src/test/resources" + SEP + "ie" + SEP + "baltimore" + SEP + "merlin-examples" + SEP + "merlin-xmldsig-twenty-three" + SEP + "signature-x509-crt.xml");
    FileInputStream fis = new FileInputStream(f);
    Document doc = XMLUtils.createDocumentBuilder(false).parse(fis);
    NodeList nl = doc.getElementsByTagNameNS(Constants.SignatureSpecNS, "X509Certificate");
    XMLX509Certificate xmlCert = new XMLX509Certificate((Element) nl.item(0), "");
    xmlCert.getX509Certificate();
// System.out.println(cert);
}
Also used : XMLX509Certificate(org.apache.xml.security.keys.content.x509.XMLX509Certificate) NodeList(org.w3c.dom.NodeList) Document(org.w3c.dom.Document) File(java.io.File) FileInputStream(java.io.FileInputStream)

Example 10 with XMLX509Certificate

use of org.apache.xml.security.keys.content.x509.XMLX509Certificate in project santuario-java by apache.

the class KeyResolverTest method testKeyResolvers.

/**
 * Test key resolvers through a KeyInfo.
 */
@org.junit.Test
public void testKeyResolvers() throws Exception {
    // 
    if ("IBM Corporation".equals(System.getProperty("java.vendor"))) {
        return;
    }
    char[] pwd = "secret".toCharArray();
    KeyStore ks = KeyStore.getInstance("JCEKS");
    FileInputStream fis = null;
    if (BASEDIR != null && !"".equals(BASEDIR)) {
        fis = new FileInputStream(BASEDIR + SEP + "src/test/resources/test.jceks");
    } else {
        fis = new FileInputStream("src/test/resources/test.jceks");
    }
    ks.load(fis, pwd);
    X509Certificate cert = (X509Certificate) ks.getCertificate("rsakey");
    PublicKey publicKey = cert.getPublicKey();
    PrivateKey privateKey = (PrivateKey) ks.getKey("rsakey", pwd);
    SecretKey secretKey = (SecretKey) ks.getKey("des3key", pwd);
    StorageResolver storage = new StorageResolver(new KeyStoreResolver(ks));
    KeyResolverSpi privateKeyResolver = new PrivateKeyResolver(ks, pwd);
    KeyResolverSpi secretKeyResolver = new SecretKeyResolver(ks, pwd);
    DocumentBuilder db = XMLUtils.createDocumentBuilder(false);
    Document doc = db.newDocument();
    KeyInfo ki;
    X509Data x509data;
    // X509Certificate hint
    ki = new KeyInfo(doc);
    ki.addStorageResolver(storage);
    x509data = new X509Data(doc);
    x509data.add(new XMLX509Certificate(doc, cert));
    ki.add(x509data);
    assertEquals(publicKey, ki.getPublicKey());
    assertNull(ki.getPrivateKey());
    ki.registerInternalKeyResolver(privateKeyResolver);
    assertEquals(privateKey, ki.getPrivateKey());
    // Issuer/Serial hint
    ki = new KeyInfo(doc);
    ki.addStorageResolver(storage);
    x509data = new X509Data(doc);
    x509data.add(new XMLX509IssuerSerial(doc, cert.getIssuerX500Principal().getName(), cert.getSerialNumber()));
    ki.add(x509data);
    assertEquals(publicKey, ki.getPublicKey());
    ki.registerInternalKeyResolver(privateKeyResolver);
    assertEquals(privateKey, ki.getPrivateKey());
    // SubjectName hint
    ki = new KeyInfo(doc);
    ki.addStorageResolver(storage);
    x509data = new X509Data(doc);
    x509data.add(new XMLX509SubjectName(doc, cert.getSubjectX500Principal().getName()));
    ki.add(x509data);
    assertEquals(publicKey, ki.getPublicKey());
    ki.registerInternalKeyResolver(privateKeyResolver);
    assertEquals(privateKey, ki.getPrivateKey());
    // SKI hint
    ki = new KeyInfo(doc);
    ki.addStorageResolver(storage);
    x509data = new X509Data(doc);
    x509data.add(new XMLX509SKI(doc, cert));
    ki.add(x509data);
    assertEquals(publicKey, ki.getPublicKey());
    ki.registerInternalKeyResolver(privateKeyResolver);
    assertEquals(privateKey, ki.getPrivateKey());
    // KeyName hint
    String rsaKeyName = "rsakey";
    ki = new KeyInfo(doc);
    ki.addKeyName(rsaKeyName);
    ki.registerInternalKeyResolver(new SingleKeyResolver(rsaKeyName, publicKey));
    assertEquals(publicKey, ki.getPublicKey());
    ki = new KeyInfo(doc);
    ki.addKeyName(rsaKeyName);
    ki.registerInternalKeyResolver(privateKeyResolver);
    assertEquals(privateKey, ki.getPrivateKey());
    ki = new KeyInfo(doc);
    ki.addKeyName(rsaKeyName);
    ki.registerInternalKeyResolver(new SingleKeyResolver(rsaKeyName, privateKey));
    assertEquals(privateKey, ki.getPrivateKey());
    String des3KeyName = "des3key";
    ki = new KeyInfo(doc);
    ki.addKeyName(des3KeyName);
    ki.registerInternalKeyResolver(secretKeyResolver);
    assertEquals(secretKey, ki.getSecretKey());
    ki = new KeyInfo(doc);
    ki.addKeyName(des3KeyName);
    ki.registerInternalKeyResolver(new SingleKeyResolver(des3KeyName, secretKey));
    assertEquals(secretKey, ki.getSecretKey());
}
Also used : SingleKeyResolver(org.apache.xml.security.keys.keyresolver.implementations.SingleKeyResolver) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PrivateKey(java.security.PrivateKey) StorageResolver(org.apache.xml.security.keys.storage.StorageResolver) RSAPublicKey(java.security.interfaces.RSAPublicKey) PublicKey(java.security.PublicKey) PrivateKeyResolver(org.apache.xml.security.keys.keyresolver.implementations.PrivateKeyResolver) XMLX509IssuerSerial(org.apache.xml.security.keys.content.x509.XMLX509IssuerSerial) Document(org.w3c.dom.Document) KeyStore(java.security.KeyStore) X509Data(org.apache.xml.security.keys.content.X509Data) FileInputStream(java.io.FileInputStream) X509Certificate(java.security.cert.X509Certificate) XMLX509Certificate(org.apache.xml.security.keys.content.x509.XMLX509Certificate) XMLX509SubjectName(org.apache.xml.security.keys.content.x509.XMLX509SubjectName) XMLX509Certificate(org.apache.xml.security.keys.content.x509.XMLX509Certificate) SecretKey(javax.crypto.SecretKey) KeyStoreResolver(org.apache.xml.security.keys.storage.implementations.KeyStoreResolver) DocumentBuilder(javax.xml.parsers.DocumentBuilder) KeyInfo(org.apache.xml.security.keys.KeyInfo) XMLX509SKI(org.apache.xml.security.keys.content.x509.XMLX509SKI) SecretKeyResolver(org.apache.xml.security.keys.keyresolver.implementations.SecretKeyResolver) KeyResolverSpi(org.apache.xml.security.keys.keyresolver.KeyResolverSpi)

Aggregations

XMLX509Certificate (org.apache.xml.security.keys.content.x509.XMLX509Certificate)9 X509Certificate (java.security.cert.X509Certificate)8 PrivateKey (java.security.PrivateKey)7 X509Data (org.apache.xml.security.keys.content.X509Data)5 Key (java.security.Key)4 KeyStoreException (java.security.KeyStoreException)4 SecretKey (javax.crypto.SecretKey)4 XMLSecurityException (org.apache.xml.security.exceptions.XMLSecurityException)4 Document (org.w3c.dom.Document)4 Element (org.w3c.dom.Element)4 XMLSecurityException (com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException)3 XMLX509Certificate (com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509Certificate)3 PublicKey (java.security.PublicKey)3 KeyInfo (org.apache.xml.security.keys.KeyInfo)3 KeyResolverException (com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException)2 FileInputStream (java.io.FileInputStream)2 Certificate (java.security.cert.Certificate)2 CertificateEncodingException (java.security.cert.CertificateEncodingException)2 EncryptedKey (org.apache.xml.security.encryption.EncryptedKey)2 XMLCipher (org.apache.xml.security.encryption.XMLCipher)2