Search in sources :

Example 1 with OutboundSecurityToken

use of org.apache.xml.security.stax.securityToken.OutboundSecurityToken in project santuario-java by apache.

the class AbstractSignatureEndingOutputProcessor method processHeaderEvent.

/*
        <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#" Id="Signature-1022834285">
            <ds:SignedInfo>
                <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
                <ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />
                <ds:Reference URI="#id-1612925417">
                    <ds:Transforms>
                        <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
                    </ds:Transforms>
                    <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
                    <ds:DigestValue>cy/khx5N6UobCJ1EbX+qnrGID2U=</ds:DigestValue>
                </ds:Reference>
                <ds:Reference URI="#Timestamp-1106985890">
                    <ds:Transforms>
                        <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
                    </ds:Transforms>
                    <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
                    <ds:DigestValue>+p5YRII6uvUdsJ7XLKkWx1CBewE=</ds:DigestValue>
                </ds:Reference>
            </ds:SignedInfo>
            <ds:SignatureValue>
                Izg1FlI9oa4gOon2vTXi7V0EpiyCUazECVGYflbXq7/3GF8ThKGDMpush/fo1I2NVjEFTfmT2WP/
                +ZG5N2jASFptrcGbsqmuLE5JbxUP1TVKb9SigKYcOQJJ8klzmVfPXnSiRZmIU+DUT2UXopWnGNFL
                TwY0Uxja4ZuI6U8m8Tg=
            </ds:SignatureValue>
            <ds:KeyInfo Id="KeyId-1043455692">
                <wsse:SecurityTokenReference xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
                    xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="STRId-1008354042">
                    <wsse:Reference xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
                        URI="#CertId-3458500" ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3" />
                </wsse:SecurityTokenReference>
            </ds:KeyInfo>
        </ds:Signature>
    */
@Override
public void processHeaderEvent(OutputProcessorChain outputProcessorChain) throws XMLStreamException, XMLSecurityException {
    OutputProcessorChain subOutputProcessorChain = outputProcessorChain.createSubChain(this);
    List<XMLSecAttribute> attributes = new ArrayList<>(1);
    if (securityProperties.isSignatureGenerateIds()) {
        attributes = new ArrayList<>(1);
        attributes.add(createAttribute(XMLSecurityConstants.ATT_NULL_Id, IDGenerator.generateID(null)));
    } else {
        attributes = Collections.emptyList();
    }
    XMLSecStartElement signatureElement = createStartElementAndOutputAsEvent(subOutputProcessorChain, XMLSecurityConstants.TAG_dsig_Signature, true, attributes);
    SignatureAlgorithm signatureAlgorithm;
    try {
        signatureAlgorithm = SignatureAlgorithmFactory.getInstance().getSignatureAlgorithm(getSecurityProperties().getSignatureAlgorithm());
    } catch (NoSuchAlgorithmException e) {
        throw new XMLSecurityException(e);
    } catch (NoSuchProviderException e) {
        throw new XMLSecurityException(e);
    }
    String tokenId = outputProcessorChain.getSecurityContext().get(XMLSecurityConstants.PROP_USE_THIS_TOKEN_ID_FOR_SIGNATURE);
    if (tokenId == null) {
        throw new XMLSecurityException("stax.keyNotFound");
    }
    SecurityTokenProvider<OutboundSecurityToken> wrappingSecurityTokenProvider = outputProcessorChain.getSecurityContext().getSecurityTokenProvider(tokenId);
    if (wrappingSecurityTokenProvider == null) {
        throw new XMLSecurityException("stax.keyNotFound");
    }
    final OutboundSecurityToken wrappingSecurityToken = wrappingSecurityTokenProvider.getSecurityToken();
    if (wrappingSecurityToken == null) {
        throw new XMLSecurityException("stax.keyNotFound");
    }
    String sigAlgorithm = getSecurityProperties().getSignatureAlgorithm();
    Key key = wrappingSecurityToken.getSecretKey(sigAlgorithm);
    // todo remove and use wrappingSecurityToken.isSymmetric or so?
    if (XMLSecurityConstants.NS_XMLDSIG_HMACSHA1.equals(sigAlgorithm)) {
        key = XMLSecurityUtils.prepareSecretKey(sigAlgorithm, key.getEncoded());
    }
    signatureAlgorithm.engineInitSign(key);
    SignedInfoProcessor signedInfoProcessor = newSignedInfoProcessor(signatureAlgorithm, signatureElement, subOutputProcessorChain);
    createStartElementAndOutputAsEvent(subOutputProcessorChain, XMLSecurityConstants.TAG_dsig_SignedInfo, false, null);
    attributes = new ArrayList<>(1);
    final String signatureCanonicalizationAlgorithm = getSecurityProperties().getSignatureCanonicalizationAlgorithm();
    attributes.add(createAttribute(XMLSecurityConstants.ATT_NULL_Algorithm, signatureCanonicalizationAlgorithm));
    createStartElementAndOutputAsEvent(subOutputProcessorChain, XMLSecurityConstants.TAG_dsig_CanonicalizationMethod, false, attributes);
    if (getSecurityProperties().isAddExcC14NInclusivePrefixes() && XMLSecurityConstants.NS_C14N_EXCL.equals(signatureCanonicalizationAlgorithm)) {
        attributes = new ArrayList<>(1);
        attributes.add(createAttribute(XMLSecurityConstants.ATT_NULL_PrefixList, signedInfoProcessor.getInclusiveNamespacePrefixes()));
        createStartElementAndOutputAsEvent(subOutputProcessorChain, XMLSecurityConstants.TAG_c14nExcl_InclusiveNamespaces, true, attributes);
        createEndElementAndOutputAsEvent(subOutputProcessorChain, XMLSecurityConstants.TAG_c14nExcl_InclusiveNamespaces);
    }
    createEndElementAndOutputAsEvent(subOutputProcessorChain, XMLSecurityConstants.TAG_dsig_CanonicalizationMethod);
    attributes = new ArrayList<>(1);
    attributes.add(createAttribute(XMLSecurityConstants.ATT_NULL_Algorithm, getSecurityProperties().getSignatureAlgorithm()));
    createStartElementAndOutputAsEvent(subOutputProcessorChain, XMLSecurityConstants.TAG_dsig_SignatureMethod, false, attributes);
    createEndElementAndOutputAsEvent(subOutputProcessorChain, XMLSecurityConstants.TAG_dsig_SignatureMethod);
    Iterator<SignaturePartDef> signaturePartDefIterator = signaturePartDefList.iterator();
    while (signaturePartDefIterator.hasNext()) {
        SignaturePartDef signaturePartDef = signaturePartDefIterator.next();
        String uriString;
        if (signaturePartDef.isExternalResource()) {
            uriString = signaturePartDef.getSigRefId();
        } else if (signaturePartDef.getSigRefId() != null) {
            if (signaturePartDef.isGenerateXPointer()) {
                uriString = "#xpointer(id('" + signaturePartDef.getSigRefId() + "'))";
            } else {
                uriString = "#" + signaturePartDef.getSigRefId();
            }
        } else {
            uriString = "";
        }
        attributes = new ArrayList<>(1);
        attributes.add(createAttribute(XMLSecurityConstants.ATT_NULL_URI, uriString));
        createStartElementAndOutputAsEvent(subOutputProcessorChain, XMLSecurityConstants.TAG_dsig_Reference, false, attributes);
        createTransformsStructureForSignature(subOutputProcessorChain, signaturePartDef);
        attributes = new ArrayList<>(1);
        attributes.add(createAttribute(XMLSecurityConstants.ATT_NULL_Algorithm, signaturePartDef.getDigestAlgo()));
        createStartElementAndOutputAsEvent(subOutputProcessorChain, XMLSecurityConstants.TAG_dsig_DigestMethod, false, attributes);
        createEndElementAndOutputAsEvent(subOutputProcessorChain, XMLSecurityConstants.TAG_dsig_DigestMethod);
        createStartElementAndOutputAsEvent(subOutputProcessorChain, XMLSecurityConstants.TAG_dsig_DigestValue, false, null);
        createCharactersAndOutputAsEvent(subOutputProcessorChain, signaturePartDef.getDigestValue());
        createEndElementAndOutputAsEvent(subOutputProcessorChain, XMLSecurityConstants.TAG_dsig_DigestValue);
        createEndElementAndOutputAsEvent(subOutputProcessorChain, XMLSecurityConstants.TAG_dsig_Reference);
    }
    createEndElementAndOutputAsEvent(subOutputProcessorChain, XMLSecurityConstants.TAG_dsig_SignedInfo);
    subOutputProcessorChain.removeProcessor(signedInfoProcessor);
    createStartElementAndOutputAsEvent(subOutputProcessorChain, XMLSecurityConstants.TAG_dsig_SignatureValue, false, null);
    final byte[] signatureValue = signedInfoProcessor.getSignatureValue();
    createCharactersAndOutputAsEvent(subOutputProcessorChain, Base64.getMimeEncoder().encodeToString(signatureValue));
    createEndElementAndOutputAsEvent(subOutputProcessorChain, XMLSecurityConstants.TAG_dsig_SignatureValue);
    if (securityProperties.isSignatureGenerateIds()) {
        attributes = new ArrayList<>(1);
        attributes.add(createAttribute(XMLSecurityConstants.ATT_NULL_Id, IDGenerator.generateID(null)));
    } else {
        attributes = Collections.emptyList();
    }
    if (!SecurityTokenConstants.KeyIdentifier_NoKeyInfo.equals(getSecurityProperties().getSignatureKeyIdentifier())) {
        createStartElementAndOutputAsEvent(subOutputProcessorChain, XMLSecurityConstants.TAG_dsig_KeyInfo, false, attributes);
        createKeyInfoStructureForSignature(subOutputProcessorChain, wrappingSecurityToken, getSecurityProperties().isUseSingleCert());
        createEndElementAndOutputAsEvent(subOutputProcessorChain, XMLSecurityConstants.TAG_dsig_KeyInfo);
    }
    createEndElementAndOutputAsEvent(subOutputProcessorChain, XMLSecurityConstants.TAG_dsig_Signature);
}
Also used : SignaturePartDef(org.apache.xml.security.stax.impl.SignaturePartDef) SignatureAlgorithm(org.apache.xml.security.stax.impl.algorithms.SignatureAlgorithm) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException) XMLSecStartElement(org.apache.xml.security.stax.ext.stax.XMLSecStartElement) OutboundSecurityToken(org.apache.xml.security.stax.securityToken.OutboundSecurityToken) XMLSecAttribute(org.apache.xml.security.stax.ext.stax.XMLSecAttribute) NoSuchProviderException(java.security.NoSuchProviderException) OutputProcessorChain(org.apache.xml.security.stax.ext.OutputProcessorChain) Key(java.security.Key)

Example 2 with OutboundSecurityToken

use of org.apache.xml.security.stax.securityToken.OutboundSecurityToken in project santuario-java by apache.

the class OutboundXMLSec method configureSignatureKeys.

private void configureSignatureKeys(final OutboundSecurityContextImpl outboundSecurityContext) throws XMLSecurityException {
    Key key = securityProperties.getSignatureKey();
    X509Certificate[] x509Certificates = securityProperties.getSignatureCerts();
    if (key instanceof PrivateKey && (x509Certificates == null || x509Certificates.length == 0) && securityProperties.getSignatureVerificationKey() == null) {
        throw new XMLSecurityException("stax.signature.publicKeyOrCertificateMissing");
    }
    final String securityTokenid = IDGenerator.generateID("SIG");
    final OutboundSecurityToken securityToken = new GenericOutboundSecurityToken(securityTokenid, SecurityTokenConstants.DefaultToken, key, x509Certificates);
    if (securityProperties.getSignatureVerificationKey() instanceof PublicKey) {
        ((GenericOutboundSecurityToken) securityToken).setPublicKey((PublicKey) securityProperties.getSignatureVerificationKey());
    }
    final SecurityTokenProvider<OutboundSecurityToken> securityTokenProvider = new SecurityTokenProvider<OutboundSecurityToken>() {

        @Override
        public OutboundSecurityToken getSecurityToken() throws XMLSecurityException {
            return securityToken;
        }

        @Override
        public String getId() {
            return securityTokenid;
        }
    };
    outboundSecurityContext.registerSecurityTokenProvider(securityTokenid, securityTokenProvider);
    outboundSecurityContext.put(XMLSecurityConstants.PROP_USE_THIS_TOKEN_ID_FOR_SIGNATURE, securityTokenid);
}
Also used : GenericOutboundSecurityToken(org.apache.xml.security.stax.impl.securityToken.GenericOutboundSecurityToken) PrivateKey(java.security.PrivateKey) OutboundSecurityToken(org.apache.xml.security.stax.securityToken.OutboundSecurityToken) GenericOutboundSecurityToken(org.apache.xml.security.stax.impl.securityToken.GenericOutboundSecurityToken) PublicKey(java.security.PublicKey) PublicKey(java.security.PublicKey) Key(java.security.Key) PrivateKey(java.security.PrivateKey) X509Certificate(java.security.cert.X509Certificate) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException) SecurityTokenProvider(org.apache.xml.security.stax.securityToken.SecurityTokenProvider)

Example 3 with OutboundSecurityToken

use of org.apache.xml.security.stax.securityToken.OutboundSecurityToken in project cxf by apache.

the class AbstractStaxBindingHandler method addKerberosToken.

protected SecurePart addKerberosToken(KerberosToken token, boolean signed, boolean endorsing, boolean encrypting) throws WSSecurityException, TokenStoreException {
    assertToken(token);
    IncludeTokenType includeToken = token.getIncludeTokenType();
    if (!isTokenRequired(includeToken)) {
        return null;
    }
    final SecurityToken secToken = getSecurityToken();
    if (secToken == null) {
        unassertPolicy(token, "Could not find KerberosToken");
    }
    // Get the kerberos token from the element
    byte[] data = null;
    if (secToken.getToken() != null) {
        String text = XMLUtils.getElementText(secToken.getToken());
        if (text != null) {
            data = org.apache.xml.security.utils.XMLUtils.decode(text);
        }
    }
    // Convert to WSS4J token
    final KerberosClientSecurityToken wss4jToken = new KerberosClientSecurityToken(data, secToken.getKey(), secToken.getId()) {

        @Override
        public Key getSecretKey(String algorithmURI) throws XMLSecurityException {
            if (secToken.getSecret() != null && algorithmURI != null && !"".equals(algorithmURI)) {
                return KeyUtils.prepareSecretKey(algorithmURI, secToken.getSecret());
            }
            return secToken.getKey();
        }
    };
    wss4jToken.setSha1Identifier(secToken.getSHA1());
    final SecurityTokenProvider<OutboundSecurityToken> kerberosSecurityTokenProvider = new SecurityTokenProvider<OutboundSecurityToken>() {

        @Override
        public OutboundSecurityToken getSecurityToken() throws WSSecurityException {
            return wss4jToken;
        }

        @Override
        public String getId() {
            return wss4jToken.getId();
        }
    };
    outboundSecurityContext.registerSecurityTokenProvider(kerberosSecurityTokenProvider.getId(), kerberosSecurityTokenProvider);
    outboundSecurityContext.put(WSSConstants.PROP_USE_THIS_TOKEN_ID_FOR_KERBEROS, kerberosSecurityTokenProvider.getId());
    if (encrypting) {
        outboundSecurityContext.put(XMLSecurityConstants.PROP_USE_THIS_TOKEN_ID_FOR_ENCRYPTION, kerberosSecurityTokenProvider.getId());
    }
    if (endorsing) {
        outboundSecurityContext.put(XMLSecurityConstants.PROP_USE_THIS_TOKEN_ID_FOR_SIGNATURE, kerberosSecurityTokenProvider.getId());
    }
    // Action
    properties.addAction(WSSConstants.KERBEROS_TOKEN);
    /*
        if (endorsing) {
            String action = (String)config.get(ConfigurationConstants.ACTION);
            config.put(ConfigurationConstants.ACTION,
                ConfigurationConstants.SIGNATURE_WITH_KERBEROS_TOKEN  + " " + action);
            // config.put(ConfigurationConstants.SIG_KEY_ID, "DirectReference");
        }
        */
    SecurePart securePart = new SecurePart(WSSConstants.TAG_WSSE_BINARY_SECURITY_TOKEN, Modifier.Element);
    securePart.setIdToSecure(wss4jToken.getId());
    return securePart;
}
Also used : GenericOutboundSecurityToken(org.apache.xml.security.stax.impl.securityToken.GenericOutboundSecurityToken) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) KerberosClientSecurityToken(org.apache.wss4j.stax.impl.securityToken.KerberosClientSecurityToken) OutboundSecurityToken(org.apache.xml.security.stax.securityToken.OutboundSecurityToken) SecurePart(org.apache.xml.security.stax.ext.SecurePart) GenericOutboundSecurityToken(org.apache.xml.security.stax.impl.securityToken.GenericOutboundSecurityToken) OutboundSecurityToken(org.apache.xml.security.stax.securityToken.OutboundSecurityToken) IncludeTokenType(org.apache.wss4j.policy.SPConstants.IncludeTokenType) KerberosClientSecurityToken(org.apache.wss4j.stax.impl.securityToken.KerberosClientSecurityToken) SecurityTokenProvider(org.apache.xml.security.stax.securityToken.SecurityTokenProvider)

Example 4 with OutboundSecurityToken

use of org.apache.xml.security.stax.securityToken.OutboundSecurityToken in project cxf by apache.

the class AbstractStaxBindingHandler method storeSecurityToken.

protected void storeSecurityToken(AbstractToken policyToken, SecurityToken tok) {
    SecurityTokenConstants.TokenType tokenType = WSSecurityTokenConstants.EncryptedKeyToken;
    if (tok.getTokenType() != null) {
        if (tok.getTokenType().startsWith(WSSConstants.NS_KERBEROS11_TOKEN_PROFILE)) {
            tokenType = WSSecurityTokenConstants.KERBEROS_TOKEN;
        } else if (tok.getTokenType().startsWith(WSSConstants.NS_SAML10_TOKEN_PROFILE) || tok.getTokenType().startsWith(WSSConstants.NS_SAML11_TOKEN_PROFILE)) {
            tokenType = WSSecurityTokenConstants.SAML_11_TOKEN;
        } else if (tok.getTokenType().startsWith(WSSConstants.NS_WSC_05_02) || tok.getTokenType().startsWith(WSSConstants.NS_WSC_05_12)) {
            tokenType = WSSecurityTokenConstants.SECURE_CONVERSATION_TOKEN;
        }
    }
    final Key key = tok.getKey();
    final byte[] secret = tok.getSecret();
    final X509Certificate[] certs = new X509Certificate[1];
    if (tok.getX509Certificate() != null) {
        certs[0] = tok.getX509Certificate();
    }
    final GenericOutboundSecurityToken encryptedKeySecurityToken = new GenericOutboundSecurityToken(tok.getId(), tokenType, key, certs) {

        @Override
        public Key getSecretKey(String algorithmURI) throws XMLSecurityException {
            if (secret != null && algorithmURI != null && !"".equals(algorithmURI)) {
                return KeyUtils.prepareSecretKey(algorithmURI, secret);
            }
            if (key != null) {
                return key;
            }
            if (secret != null) {
                String jceAlg = JCEMapper.getJCEKeyAlgorithmFromURI(algorithmURI);
                if (jceAlg == null || "".equals(jceAlg)) {
                    jceAlg = "HmacSHA1";
                }
                return new SecretKeySpec(secret, jceAlg);
            }
            return super.getSecretKey(algorithmURI);
        }
    };
    // Store a DOM Element reference if it exists
    Element ref;
    if (isTokenRequired(policyToken.getIncludeTokenType())) {
        ref = tok.getAttachedReference();
    } else {
        ref = tok.getUnattachedReference();
    }
    if (ref != null && policyToken instanceof IssuedToken) {
        encryptedKeySecurityToken.setCustomTokenReference(ref);
    }
    final SecurityTokenProvider<OutboundSecurityToken> encryptedKeySecurityTokenProvider = new SecurityTokenProvider<OutboundSecurityToken>() {

        @Override
        public OutboundSecurityToken getSecurityToken() throws XMLSecurityException {
            return encryptedKeySecurityToken;
        }

        @Override
        public String getId() {
            return encryptedKeySecurityToken.getId();
        }
    };
    encryptedKeySecurityToken.setSha1Identifier(tok.getSHA1());
    outboundSecurityContext.registerSecurityTokenProvider(encryptedKeySecurityTokenProvider.getId(), encryptedKeySecurityTokenProvider);
    outboundSecurityContext.put(XMLSecurityConstants.PROP_USE_THIS_TOKEN_ID_FOR_ENCRYPTION, encryptedKeySecurityTokenProvider.getId());
    outboundSecurityContext.put(XMLSecurityConstants.PROP_USE_THIS_TOKEN_ID_FOR_SIGNATURE, encryptedKeySecurityTokenProvider.getId());
    outboundSecurityContext.put(WSSConstants.PROP_USE_THIS_TOKEN_ID_FOR_CUSTOM_TOKEN, encryptedKeySecurityTokenProvider.getId());
}
Also used : Element(org.w3c.dom.Element) IssuedToken(org.apache.wss4j.policy.model.IssuedToken) SecurityTokenConstants(org.apache.xml.security.stax.securityToken.SecurityTokenConstants) WSSecurityTokenConstants(org.apache.wss4j.stax.securityToken.WSSecurityTokenConstants) X509Certificate(java.security.cert.X509Certificate) GenericOutboundSecurityToken(org.apache.xml.security.stax.impl.securityToken.GenericOutboundSecurityToken) GenericOutboundSecurityToken(org.apache.xml.security.stax.impl.securityToken.GenericOutboundSecurityToken) OutboundSecurityToken(org.apache.xml.security.stax.securityToken.OutboundSecurityToken) SecretKeySpec(javax.crypto.spec.SecretKeySpec) Key(java.security.Key) SecurityTokenProvider(org.apache.xml.security.stax.securityToken.SecurityTokenProvider)

Example 5 with OutboundSecurityToken

use of org.apache.xml.security.stax.securityToken.OutboundSecurityToken in project santuario-java by apache.

the class XMLEncryptOutputProcessor method createInternalEncryptionOutputProcessor.

/**
 * Override this method to return a different AbstractInternalEncryptionOutputProcessor instance
 * which will write out the KeyInfo contents in the EncryptedData.
 */
protected AbstractInternalEncryptionOutputProcessor createInternalEncryptionOutputProcessor(EncryptionPartDef encryptionPartDef, XMLSecStartElement startElement, String encoding, final OutboundSecurityToken keyWrappingToken) throws XMLStreamException, XMLSecurityException {
    final AbstractInternalEncryptionOutputProcessor processor = new AbstractInternalEncryptionOutputProcessor(encryptionPartDef, startElement, encoding) {

        @Override
        protected void createKeyInfoStructure(OutputProcessorChain outputProcessorChain) throws XMLStreamException, XMLSecurityException {
            if (keyWrappingToken == null) {
                // Do not write out a KeyInfo element
                return;
            }
            final String encryptionKeyTransportAlgorithm = getSecurityProperties().getEncryptionKeyTransportAlgorithm();
            PublicKey pubKey = keyWrappingToken.getPublicKey();
            Key secretKey = keyWrappingToken.getSecretKey(encryptionKeyTransportAlgorithm);
            if (pubKey == null && secretKey == null) {
                // Do not write out a KeyInfo element
                return;
            }
            createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_KeyInfo, true, null);
            List<XMLSecAttribute> attributes = new ArrayList<>(1);
            String keyId = IDGenerator.generateID("EK");
            attributes.add(createAttribute(XMLSecurityConstants.ATT_NULL_Id, keyId));
            createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc_EncryptedKey, true, attributes);
            attributes = new ArrayList<>(1);
            attributes.add(createAttribute(XMLSecurityConstants.ATT_NULL_Algorithm, encryptionKeyTransportAlgorithm));
            createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc_EncryptionMethod, false, attributes);
            final String encryptionKeyTransportDigestAlgorithm = getSecurityProperties().getEncryptionKeyTransportDigestAlgorithm();
            final String encryptionKeyTransportMGFAlgorithm = getSecurityProperties().getEncryptionKeyTransportMGFAlgorithm();
            if (XMLSecurityConstants.NS_XENC11_RSAOAEP.equals(encryptionKeyTransportAlgorithm) || XMLSecurityConstants.NS_XENC_RSAOAEPMGF1P.equals(encryptionKeyTransportAlgorithm)) {
                byte[] oaepParams = getSecurityProperties().getEncryptionKeyTransportOAEPParams();
                if (oaepParams != null) {
                    createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc_OAEPparams, false, null);
                    createCharactersAndOutputAsEvent(outputProcessorChain, Base64.getMimeEncoder().encodeToString(oaepParams));
                    createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc_OAEPparams);
                }
                if (encryptionKeyTransportDigestAlgorithm != null) {
                    attributes = new ArrayList<>(1);
                    attributes.add(createAttribute(XMLSecurityConstants.ATT_NULL_Algorithm, encryptionKeyTransportDigestAlgorithm));
                    createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_DigestMethod, true, attributes);
                    createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_DigestMethod);
                }
                if (encryptionKeyTransportMGFAlgorithm != null) {
                    attributes = new ArrayList<>(1);
                    attributes.add(createAttribute(XMLSecurityConstants.ATT_NULL_Algorithm, encryptionKeyTransportMGFAlgorithm));
                    createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc11_MGF, true, attributes);
                    createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc11_MGF);
                }
            }
            createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc_EncryptionMethod);
            createKeyInfoStructureForEncryptedKey(outputProcessorChain, keyWrappingToken);
            createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc_CipherData, false, null);
            createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc_CipherValue, false, null);
            // encrypt the symmetric session key with the public key from the receiver:
            String jceid = JCEAlgorithmMapper.translateURItoJCEID(encryptionKeyTransportAlgorithm);
            if (jceid == null) {
                throw new XMLSecurityException("algorithms.NoSuchMap", new Object[] { encryptionKeyTransportAlgorithm });
            }
            try {
                Cipher cipher = Cipher.getInstance(jceid);
                AlgorithmParameterSpec algorithmParameterSpec = null;
                if (XMLSecurityConstants.NS_XENC11_RSAOAEP.equals(encryptionKeyTransportAlgorithm) || XMLSecurityConstants.NS_XENC_RSAOAEPMGF1P.equals(encryptionKeyTransportAlgorithm)) {
                    String jceDigestAlgorithm = "SHA-1";
                    if (encryptionKeyTransportDigestAlgorithm != null) {
                        jceDigestAlgorithm = JCEAlgorithmMapper.translateURItoJCEID(encryptionKeyTransportDigestAlgorithm);
                    }
                    PSource.PSpecified pSource = PSource.PSpecified.DEFAULT;
                    byte[] oaepParams = getSecurityProperties().getEncryptionKeyTransportOAEPParams();
                    if (oaepParams != null) {
                        pSource = new PSource.PSpecified(oaepParams);
                    }
                    MGF1ParameterSpec mgfParameterSpec = new MGF1ParameterSpec("SHA-1");
                    if (encryptionKeyTransportMGFAlgorithm != null) {
                        String jceMGFAlgorithm = JCEAlgorithmMapper.translateURItoJCEID(encryptionKeyTransportMGFAlgorithm);
                        mgfParameterSpec = new MGF1ParameterSpec(jceMGFAlgorithm);
                    }
                    algorithmParameterSpec = new OAEPParameterSpec(jceDigestAlgorithm, "MGF1", mgfParameterSpec, pSource);
                }
                if (pubKey != null) {
                    cipher.init(Cipher.WRAP_MODE, pubKey, algorithmParameterSpec);
                } else {
                    cipher.init(Cipher.WRAP_MODE, secretKey, algorithmParameterSpec);
                }
                String tokenId = outputProcessorChain.getSecurityContext().get(XMLSecurityConstants.PROP_USE_THIS_TOKEN_ID_FOR_ENCRYPTION);
                SecurityTokenProvider<OutboundSecurityToken> securityTokenProvider = outputProcessorChain.getSecurityContext().getSecurityTokenProvider(tokenId);
                final OutboundSecurityToken securityToken = securityTokenProvider.getSecurityToken();
                Key sessionKey = securityToken.getSecretKey(getSecurityProperties().getEncryptionSymAlgorithm());
                if (pubKey != null) {
                    int blockSize = cipher.getBlockSize();
                    if (blockSize > 0 && blockSize < sessionKey.getEncoded().length) {
                        throw new XMLSecurityException("stax.unsupportedKeyTransp");
                    }
                }
                byte[] encryptedEphemeralKey = cipher.wrap(sessionKey);
                createCharactersAndOutputAsEvent(outputProcessorChain, Base64.getMimeEncoder().encodeToString(encryptedEphemeralKey));
            } catch (NoSuchPaddingException e) {
                throw new XMLSecurityException(e);
            } catch (NoSuchAlgorithmException e) {
                throw new XMLSecurityException(e);
            } catch (InvalidKeyException e) {
                throw new XMLSecurityException(e);
            } catch (IllegalBlockSizeException e) {
                throw new XMLSecurityException(e);
            } catch (InvalidAlgorithmParameterException e) {
                throw new XMLSecurityException(e);
            }
            createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc_CipherValue);
            createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc_CipherData);
            createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_xenc_EncryptedKey);
            createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_KeyInfo);
        }

        protected void createKeyInfoStructureForEncryptedKey(OutputProcessorChain outputProcessorChain, OutboundSecurityToken securityToken) throws XMLStreamException, XMLSecurityException {
            SecurityTokenConstants.KeyIdentifier keyIdentifier = getSecurityProperties().getEncryptionKeyIdentifier();
            X509Certificate[] x509Certificates = securityToken.getX509Certificates();
            if (x509Certificates == null) {
                if (securityToken.getPublicKey() != null && SecurityTokenConstants.KeyIdentifier_KeyValue.equals(keyIdentifier)) {
                    createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_KeyInfo, true, null);
                    XMLSecurityUtils.createKeyValueTokenStructure(this, outputProcessorChain, securityToken.getPublicKey());
                    createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_KeyInfo);
                }
                return;
            }
            if (!SecurityTokenConstants.KeyIdentifier_NoKeyInfo.equals(keyIdentifier)) {
                createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_KeyInfo, true, null);
                if (keyIdentifier == null || SecurityTokenConstants.KeyIdentifier_IssuerSerial.equals(keyIdentifier)) {
                    XMLSecurityUtils.createX509IssuerSerialStructure(this, outputProcessorChain, x509Certificates);
                } else if (SecurityTokenConstants.KeyIdentifier_KeyValue.equals(keyIdentifier)) {
                    XMLSecurityUtils.createKeyValueTokenStructure(this, outputProcessorChain, x509Certificates);
                } else if (SecurityTokenConstants.KeyIdentifier_SkiKeyIdentifier.equals(keyIdentifier)) {
                    XMLSecurityUtils.createX509SubjectKeyIdentifierStructure(this, outputProcessorChain, x509Certificates);
                } else if (SecurityTokenConstants.KeyIdentifier_X509KeyIdentifier.equals(keyIdentifier)) {
                    XMLSecurityUtils.createX509CertificateStructure(this, outputProcessorChain, x509Certificates);
                } else if (SecurityTokenConstants.KeyIdentifier_X509SubjectName.equals(keyIdentifier)) {
                    XMLSecurityUtils.createX509SubjectNameStructure(this, outputProcessorChain, x509Certificates);
                } else if (SecurityTokenConstants.KeyIdentifier_KeyName.equals(keyIdentifier)) {
                    String keyName = getSecurityProperties().getEncryptionKeyName();
                    XMLSecurityUtils.createKeyNameTokenStructure(this, outputProcessorChain, keyName);
                } else {
                    throw new XMLSecurityException("stax.unsupportedToken", new Object[] { keyIdentifier });
                }
                createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_KeyInfo);
            }
        }
    };
    processor.getAfterProcessors().add(XMLEncryptOutputProcessor.class.getName());
    return processor;
}
Also used : ArrayList(java.util.ArrayList) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) OutboundSecurityToken(org.apache.xml.security.stax.securityToken.OutboundSecurityToken) XMLSecAttribute(org.apache.xml.security.stax.ext.stax.XMLSecAttribute) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) SecurityTokenConstants(org.apache.xml.security.stax.securityToken.SecurityTokenConstants) PSource(javax.crypto.spec.PSource) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException) X509Certificate(java.security.cert.X509Certificate) OAEPParameterSpec(javax.crypto.spec.OAEPParameterSpec) Cipher(javax.crypto.Cipher) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec) MGF1ParameterSpec(java.security.spec.MGF1ParameterSpec)

Aggregations

OutboundSecurityToken (org.apache.xml.security.stax.securityToken.OutboundSecurityToken)7 Key (java.security.Key)4 X509Certificate (java.security.cert.X509Certificate)4 XMLSecurityException (org.apache.xml.security.exceptions.XMLSecurityException)4 GenericOutboundSecurityToken (org.apache.xml.security.stax.impl.securityToken.GenericOutboundSecurityToken)4 SecurityTokenProvider (org.apache.xml.security.stax.securityToken.SecurityTokenProvider)4 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)2 PrivateKey (java.security.PrivateKey)2 PublicKey (java.security.PublicKey)2 XMLSecAttribute (org.apache.xml.security.stax.ext.stax.XMLSecAttribute)2 XMLSecStartElement (org.apache.xml.security.stax.ext.stax.XMLSecStartElement)2 SecurityTokenConstants (org.apache.xml.security.stax.securityToken.SecurityTokenConstants)2 NoSuchProviderException (java.security.NoSuchProviderException)1 AlgorithmParameterSpec (java.security.spec.AlgorithmParameterSpec)1 MGF1ParameterSpec (java.security.spec.MGF1ParameterSpec)1 ArrayList (java.util.ArrayList)1 Cipher (javax.crypto.Cipher)1 IllegalBlockSizeException (javax.crypto.IllegalBlockSizeException)1 KeyGenerator (javax.crypto.KeyGenerator)1 NoSuchPaddingException (javax.crypto.NoSuchPaddingException)1