Search in sources :

Example 11 with X509Data

use of org.apache.xml.security.keys.content.X509Data in project cxf by apache.

the class RESTSecurityTokenServiceImpl method issueToken.

private RequestSecurityTokenResponseType issueToken(String tokenType, String keyType, List<String> requestedClaims, String appliesTo) {
    String tokenTypeToUse = tokenType;
    if (tokenTypeMap != null && tokenTypeMap.containsKey(tokenTypeToUse)) {
        tokenTypeToUse = tokenTypeMap.get(tokenTypeToUse);
    }
    String keyTypeToUse = keyType;
    if (DEFAULT_KEY_TYPE_MAP.containsKey(keyTypeToUse)) {
        keyTypeToUse = DEFAULT_KEY_TYPE_MAP.get(keyTypeToUse);
    }
    ObjectFactory of = new ObjectFactory();
    RequestSecurityTokenType request = of.createRequestSecurityTokenType();
    request.getAny().add(of.createTokenType(tokenTypeToUse));
    request.getAny().add(of.createRequestType("http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue"));
    String desiredKeyType = keyTypeToUse != null ? keyTypeToUse : defaultKeyType;
    request.getAny().add(of.createKeyType(desiredKeyType));
    // Add the TLS client Certificate as the UseKey Element if the KeyType is PublicKey
    if (STSConstants.PUBLIC_KEY_KEYTYPE.equals(desiredKeyType)) {
        X509Certificate clientCert = getTLSClientCertificate();
        if (clientCert != null) {
            Document doc = DOMUtils.getEmptyDocument();
            Element keyInfoElement = doc.createElementNS("http://www.w3.org/2000/09/xmldsig#", "KeyInfo");
            try {
                X509Data certElem = new X509Data(doc);
                certElem.addCertificate(clientCert);
                keyInfoElement.appendChild(certElem.getElement());
                UseKeyType useKeyType = of.createUseKeyType();
                useKeyType.setAny(keyInfoElement);
                JAXBElement<UseKeyType> useKey = of.createUseKey(useKeyType);
                request.getAny().add(useKey);
            } catch (XMLSecurityException ex) {
                LOG.warning(ex.getMessage());
            }
        }
    }
    // Claims
    if (requestedClaims == null || requestedClaims.isEmpty()) {
        requestedClaims = defaultClaims;
    }
    if (requestedClaims != null && !requestedClaims.isEmpty()) {
        ClaimsType claimsType = of.createClaimsType();
        claimsType.setDialect(CLAIM_TYPE_NS);
        JAXBElement<ClaimsType> claims = of.createClaims(claimsType);
        for (String claim : requestedClaims) {
            if (claimTypeMap != null && claimTypeMap.containsKey(claim)) {
                claim = claimTypeMap.get(claim);
            }
            Document doc = DOMUtils.createDocument();
            Element claimElement = doc.createElementNS(CLAIM_TYPE_NS, CLAIM_TYPE);
            claimElement.setAttributeNS(null, "Uri", claim);
            claimElement.setAttributeNS(null, "Optional", Boolean.toString(requestClaimsOptional));
            claimsType.getAny().add(claimElement);
        }
        request.getAny().add(claims);
    }
    if (appliesTo != null) {
        String wspNamespace = "http://www.w3.org/ns/ws-policy";
        Document doc = DOMUtils.createDocument();
        Element appliesToElement = doc.createElementNS(wspNamespace, "AppliesTo");
        String addressingNamespace = "http://www.w3.org/2005/08/addressing";
        Element eprElement = doc.createElementNS(addressingNamespace, "EndpointReference");
        Element addressElement = doc.createElementNS(addressingNamespace, "Address");
        addressElement.setTextContent(appliesTo);
        eprElement.appendChild(addressElement);
        appliesToElement.appendChild(eprElement);
        request.getAny().add(appliesToElement);
    }
    // request.setContext(null);
    return processRequest(Action.issue, request);
}
Also used : ObjectFactory(org.apache.cxf.ws.security.sts.provider.model.ObjectFactory) ClaimsType(org.apache.cxf.ws.security.sts.provider.model.ClaimsType) RequestSecurityTokenType(org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenType) JAXBElement(javax.xml.bind.JAXBElement) Element(org.w3c.dom.Element) UseKeyType(org.apache.cxf.ws.security.sts.provider.model.UseKeyType) Document(org.w3c.dom.Document) X509Data(org.apache.xml.security.keys.content.X509Data) X509Certificate(java.security.cert.X509Certificate) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException)

Example 12 with X509Data

use of org.apache.xml.security.keys.content.X509Data in project cxf by apache.

the class X509TokenValidator method validateToken.

/**
 * Validate a Token using the given TokenValidatorParameters.
 */
public TokenValidatorResponse validateToken(TokenValidatorParameters tokenParameters) {
    LOG.fine("Validating X.509 Token");
    STSPropertiesMBean stsProperties = tokenParameters.getStsProperties();
    CallbackHandler callbackHandler = stsProperties.getCallbackHandler();
    // See CXF-4028
    Crypto crypto = stsProperties.getEncryptionCrypto();
    if (crypto == null) {
        crypto = stsProperties.getSignatureCrypto();
    }
    RequestData requestData = new RequestData();
    requestData.setSigVerCrypto(crypto);
    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);
    final BinarySecurity binarySecurity;
    if (validateTarget.isBinarySecurityToken()) {
        BinarySecurityTokenType binarySecurityType = (BinarySecurityTokenType) validateTarget.getToken();
        // Test the encoding type
        String encodingType = binarySecurityType.getEncodingType();
        if (!BASE64_ENCODING.equals(encodingType)) {
            LOG.fine("Bad encoding type attribute specified: " + encodingType);
            return response;
        }
        // 
        // Turn the received JAXB object into a DOM element
        // 
        Document doc = DOMUtils.getEmptyDocument();
        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.getEmptyDocument();
            binarySecurity = new X509Security(doc);
            binarySecurity.setEncodingType(BASE64_ENCODING);
            X509Data x509Data = new X509Data((Element) validateTarget.getToken(), "");
            if (x509Data.containsCertificate()) {
                X509Certificate cert = x509Data.itemCertificate(0).getX509Certificate();
                ((X509Security) binarySecurity).setX509Certificate(cert);
            }
        } catch (XMLSecurityException ex) {
            LOG.log(Level.WARNING, "", ex);
            return response;
        }
    } else {
        return response;
    }
    // 
    try {
        Credential credential = new Credential();
        credential.setBinarySecurityToken(binarySecurity);
        if (crypto != null) {
            X509Certificate cert = ((X509Security) binarySecurity).getX509Certificate(crypto);
            credential.setCertificates(new X509Certificate[] { cert });
        }
        Credential returnedCredential = validator.validate(credential, requestData);
        Principal principal = returnedCredential.getPrincipal();
        if (principal == null) {
            principal = returnedCredential.getCertificates()[0].getSubjectX500Principal();
        }
        response.setPrincipal(principal);
        validateTarget.setState(STATE.VALID);
        LOG.fine("X.509 Token successfully validated");
    } catch (WSSecurityException ex) {
        LOG.log(Level.WARNING, "", ex);
    }
    return response;
}
Also used : CallbackHandler(javax.security.auth.callback.CallbackHandler) Credential(org.apache.wss4j.dom.validate.Credential) BinarySecurity(org.apache.wss4j.common.token.BinarySecurity) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) Document(org.w3c.dom.Document) X509Data(org.apache.xml.security.keys.content.X509Data) X509Certificate(java.security.cert.X509Certificate) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException) Crypto(org.apache.wss4j.common.crypto.Crypto) STSPropertiesMBean(org.apache.cxf.sts.STSPropertiesMBean) 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) Principal(java.security.Principal)

Example 13 with X509Data

use of org.apache.xml.security.keys.content.X509Data in project OpenAM by OpenRock.

the class AMEncryptionProvider method encryptAndReplace.

/**
     * Encrypts the given XML element in a given XML Context document.
     * @param doc the context XML Document.
     * @param element Element to be encrypted.
     * @param secretKeyAlg Encryption Key Algorithm.
     * @param keyStrength Encryption Key Strength.
     * @param kek Key Encryption Key.
     * @param kekStrength Key Encryption Key Strength,
     * @param providerID Provider ID
     * @param isEncryptResourceID A flag indicates whether it's to encrypt
     * 		ResourceID or not.
     * @return org.w3c.dom.Document EncryptedResourceID XML Document if
     * 		isEncryptResourceID is set. Otherwise, return the XML Document
     *		replaced with encrypted data for a given XML element.
     */
private org.w3c.dom.Document encryptAndReplace(org.w3c.dom.Document doc, org.w3c.dom.Element element, java.lang.String secretKeyAlg, int keyStrength, java.security.Key kek, int kekStrength, String providerID, boolean isEncryptResourceID) throws EncryptionException {
    if (doc == null || element == null || kek == null) {
        EncryptionUtils.debug.error("AMEncryptionProvider.encryptAnd" + "Replace: Null values");
        throw new EncryptionException(EncryptionUtils.bundle.getString("nullValues"));
    }
    SecretKey secretKey = null;
    String secretKeyAlgShortName = getEncryptionAlgorithmShortName(secretKeyAlg);
    if (providerID != null) {
        if (keyMap.containsKey(providerID)) {
            secretKey = (SecretKey) keyMap.get(providerID);
        } else {
            secretKey = generateSecretKey(secretKeyAlgShortName, keyStrength);
            keyMap.put(providerID, secretKey);
        }
    } else {
        secretKey = generateSecretKey(secretKeyAlgShortName, keyStrength);
    }
    if (secretKey == null) {
        throw new EncryptionException(EncryptionUtils.bundle.getString("generateKeyError"));
    }
    try {
        XMLCipher cipher = null;
        String keyEncAlg = kek.getAlgorithm();
        if (keyEncAlg.equals(EncryptionConstants.RSA)) {
            cipher = XMLCipher.getInstance(XMLCipher.RSA_v1dot5);
        } else if (keyEncAlg.equals(EncryptionConstants.TRIPLEDES)) {
            cipher = XMLCipher.getInstance(XMLCipher.TRIPLEDES_KeyWrap);
        } else if (keyEncAlg.equals(EncryptionConstants.AES)) {
            if (kekStrength == 0 || kekStrength == 128) {
                cipher = XMLCipher.getInstance(XMLCipher.AES_128_KeyWrap);
            } else if (kekStrength == 192) {
                cipher = XMLCipher.getInstance(XMLCipher.AES_192_KeyWrap);
            } else if (kekStrength == 256) {
                cipher = XMLCipher.getInstance(XMLCipher.AES_256_KeyWrap);
            } else {
                throw new EncryptionException(EncryptionUtils.bundle.getString("invalidKeyStrength"));
            }
        } else {
            throw new EncryptionException(EncryptionUtils.bundle.getString("unsupportedKeyAlg"));
        }
        // Encrypt the key with key encryption key
        cipher.init(XMLCipher.WRAP_MODE, kek);
        EncryptedKey encryptedKey = cipher.encryptKey(doc, secretKey);
        KeyInfo insideKi = new KeyInfo(doc);
        X509Data x509Data = new X509Data(doc);
        x509Data.addCertificate((X509Certificate) keyProvider.getCertificate((PublicKey) kek));
        insideKi.add(x509Data);
        encryptedKey.setKeyInfo(insideKi);
        String ekID = null;
        if (isEncryptResourceID) {
            ekID = com.sun.identity.saml.common.SAMLUtils.generateID();
            encryptedKey.setId(ekID);
        }
        if (EncryptionUtils.debug.messageEnabled()) {
            EncryptionUtils.debug.message("AMEncryptionProvider.encrypt" + "AndReplace: Encrypted key = " + toString(cipher.martial(doc, encryptedKey)));
        }
        String encAlgorithm = getEncryptionAlgorithm(secretKeyAlgShortName, keyStrength);
        cipher = XMLCipher.getInstance(encAlgorithm);
        cipher.init(XMLCipher.ENCRYPT_MODE, secretKey);
        EncryptedData builder = cipher.getEncryptedData();
        KeyInfo builderKeyInfo = builder.getKeyInfo();
        if (builderKeyInfo == null) {
            builderKeyInfo = new KeyInfo(doc);
            builder.setKeyInfo(builderKeyInfo);
        }
        if (isEncryptResourceID) {
            builderKeyInfo.addKeyName(providerID);
            builderKeyInfo.addRetrievalMethod("#" + ekID, null, "http://www.w3.org/2001/04/xmlenc#EncryptedKey");
        } else {
            builderKeyInfo.add(encryptedKey);
        }
        Document result = cipher.doFinal(doc, element);
        if (isEncryptResourceID) {
            Element ee = (Element) result.getElementsByTagNameNS("http://www.w3.org/2001/04/xmlenc#", "EncryptedData").item(0);
            Node parentNode = ee.getParentNode();
            Element newone = result.createElementNS("urn:liberty:disco:2003-08", "EncryptedResourceID");
            parentNode.replaceChild(newone, ee);
            newone.appendChild(ee);
            Element ek = cipher.martial(doc, encryptedKey);
            Element carriedName = doc.createElementNS("http://www.w3.org/2001/04/xmlenc#", "xenc:CarriedKeyName");
            carriedName.appendChild(doc.createTextNode(providerID));
            ek.appendChild(carriedName);
            newone.appendChild(ek);
        }
        return result;
    } catch (Exception xe) {
        EncryptionUtils.debug.error("AMEncryptionProvider.encryptAnd" + "Replace: XML Encryption error", xe);
        throw new EncryptionException(xe);
    }
}
Also used : SecretKey(javax.crypto.SecretKey) EncryptedKey(org.apache.xml.security.encryption.EncryptedKey) KeyInfo(org.apache.xml.security.keys.KeyInfo) Element(org.w3c.dom.Element) Node(org.w3c.dom.Node) XMLCipher(org.apache.xml.security.encryption.XMLCipher) EncryptedData(org.apache.xml.security.encryption.EncryptedData) Document(org.w3c.dom.Document) X509Data(org.apache.xml.security.keys.content.X509Data) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 14 with X509Data

use of org.apache.xml.security.keys.content.X509Data 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 15 with X509Data

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

the class SignatureVerificationTest method testSubjectSKI.

@Test
public void testSubjectSKI() throws Exception {
    // 
    if ("IBM Corporation".equals(System.getProperty("java.vendor"))) {
        return;
    }
    // Read in plaintext document
    InputStream sourceDocument = this.getClass().getClassLoader().getResourceAsStream("ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
    DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
    Document document = builder.parse(sourceDocument);
    // Set up the Key
    KeyStore keyStore = KeyStore.getInstance("JCEKS");
    keyStore.load(this.getClass().getClassLoader().getResource("test.jceks").openStream(), "secret".toCharArray());
    Key key = keyStore.getKey("rsakey", "secret".toCharArray());
    X509Certificate cert = (X509Certificate) keyStore.getCertificate("rsakey");
    // Sign using DOM
    List<String> localNames = new ArrayList<>();
    localNames.add("PaymentInfo");
    XMLSignature sig = signUsingDOM("http://www.w3.org/2000/09/xmldsig#rsa-sha1", document, localNames, key);
    // Add KeyInfo
    KeyInfo keyInfo = sig.getKeyInfo();
    X509Data x509Data = new X509Data(sig.getDocument());
    x509Data.addSKI(cert);
    keyInfo.add(x509Data);
    // XMLUtils.outputDOM(document, System.out);
    // Convert Document to a Stream Reader
    javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    transformer.transform(new DOMSource(document), new StreamResult(baos));
    XMLStreamReader xmlStreamReader = null;
    try (InputStream is = new ByteArrayInputStream(baos.toByteArray())) {
        xmlStreamReader = xmlInputFactory.createXMLStreamReader(is);
    }
    // Verify signature
    XMLSecurityProperties properties = new XMLSecurityProperties();
    properties.setSignatureVerificationKey(cert.getPublicKey());
    InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
    TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
    XMLStreamReader securityStreamReader = inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
    document = StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
    // Check the SecurityEvents
    checkSecurityEvents(securityEventListener);
    checkSignedElementSecurityEvents(securityEventListener);
    checkSignatureToken(securityEventListener, cert, null, SecurityTokenConstants.KeyIdentifier_SkiKeyIdentifier);
    SignedElementSecurityEvent signedElementSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.SignedElement);
    X509TokenSecurityEvent x509TokenSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.X509Token);
    String signedElementCorrelationID = signedElementSecurityEvent.getCorrelationID();
    String x509TokenCorrelationID = x509TokenSecurityEvent.getCorrelationID();
    List<SecurityEvent> signatureSecurityEvents = new ArrayList<>();
    List<SecurityEvent> signedElementSecurityEvents = new ArrayList<>();
    List<SecurityEvent> securityEvents = securityEventListener.getSecurityEvents();
    for (int i = 0; i < securityEvents.size(); i++) {
        SecurityEvent securityEvent = securityEvents.get(i);
        if (securityEvent.getCorrelationID().equals(signedElementCorrelationID)) {
            signedElementSecurityEvents.add(securityEvent);
        } else if (securityEvent.getCorrelationID().equals(x509TokenCorrelationID)) {
            signatureSecurityEvents.add(securityEvent);
        }
    }
    Assert.assertEquals(4, signatureSecurityEvents.size());
    Assert.assertEquals(3, signedElementSecurityEvents.size());
    Assert.assertEquals(securityEventListener.getSecurityEvents().size(), signatureSecurityEvents.size() + signedElementSecurityEvents.size());
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) XMLStreamReader(javax.xml.stream.XMLStreamReader) ArrayList(java.util.ArrayList) Document(org.w3c.dom.Document) X509Data(org.apache.xml.security.keys.content.X509Data) KeyInfo(org.apache.xml.security.keys.KeyInfo) XMLSignature(org.apache.xml.security.signature.XMLSignature) StreamResult(javax.xml.transform.stream.StreamResult) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) DocumentBuilder(javax.xml.parsers.DocumentBuilder) ByteArrayInputStream(java.io.ByteArrayInputStream) Key(java.security.Key) SecretKey(javax.crypto.SecretKey) Test(org.junit.Test)

Aggregations

X509Data (org.apache.xml.security.keys.content.X509Data)24 X509Certificate (java.security.cert.X509Certificate)15 KeyInfo (org.apache.xml.security.keys.KeyInfo)13 SecretKey (javax.crypto.SecretKey)10 Document (org.w3c.dom.Document)10 ByteArrayInputStream (java.io.ByteArrayInputStream)8 KeyStore (java.security.KeyStore)8 PrivateKey (java.security.PrivateKey)8 ArrayList (java.util.ArrayList)8 DocumentBuilder (javax.xml.parsers.DocumentBuilder)8 ByteArrayOutputStream (java.io.ByteArrayOutputStream)7 InputStream (java.io.InputStream)7 XMLStreamReader (javax.xml.stream.XMLStreamReader)7 DOMSource (javax.xml.transform.dom.DOMSource)7 StreamResult (javax.xml.transform.stream.StreamResult)7 XMLSecurityException (org.apache.xml.security.exceptions.XMLSecurityException)7 Test (org.junit.Test)7 Key (java.security.Key)5 XMLX509Certificate (org.apache.xml.security.keys.content.x509.XMLX509Certificate)5 XMLX509IssuerSerial (org.apache.xml.security.keys.content.x509.XMLX509IssuerSerial)5