Search in sources :

Example 1 with Transforms

use of org.apache.xml.security.transforms.Transforms in project OpenAM by OpenRock.

the class AMSignatureProvider method signWithWSSSAMLTokenProfile.

/**
     * Sign part of the xml document referered by the supplied a list
     * of id attributes of nodes
     * @param doc XML dom object
     * @param cert Signer's certificate
     * @param assertionID assertion ID
     * @param algorithm XML signature algorithm
     * @param ids list of id attribute values of nodes to be signed
     * @param wsfVersion the web services version.
     * @return SAML Security Token  signature
     * @throws XMLSignatureException if the document could not be signed
     */
public Element signWithWSSSAMLTokenProfile(Document doc, java.security.cert.Certificate cert, String assertionID, String algorithm, List ids, String wsfVersion) throws XMLSignatureException {
    if (doc == null) {
        SAMLUtilsCommon.debug.error("signXML: doc is null.");
        throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("nullInput"));
    }
    if (cert == null) {
        SAMLUtilsCommon.debug.error("signWithWSSSAMLTokenProfile: " + "Certificate is null");
        throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("nullInput"));
    }
    if (assertionID == null) {
        SAMLUtilsCommon.debug.error("signWithWSSSAMLTokenProfile: " + "AssertionID is null");
        throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("nullInput"));
    }
    this.wsfVersion = wsfVersion;
    String wsseNS = SAMLConstants.NS_WSSE;
    String wsuNS = SAMLConstants.NS_WSU;
    if ((wsfVersion != null) && (wsfVersion.equals(SOAPBindingConstants.WSF_11_VERSION))) {
        wsseNS = WSSEConstants.NS_WSSE_WSF11;
        wsuNS = WSSEConstants.NS_WSU_WSF11;
    }
    Element root = (Element) doc.getDocumentElement().getElementsByTagNameNS(wsseNS, SAMLConstants.TAG_SECURITY).item(0);
    XMLSignature signature = null;
    try {
        ElementProxy.setDefaultPrefix(Constants.SignatureSpecNS, SAMLConstants.PREFIX_DS);
        Element wsucontext = org.apache.xml.security.utils.XMLUtils.createDSctx(doc, "wsu", wsuNS);
        NodeList wsuNodes = (NodeList) XPathAPI.selectNodeList(doc, "//*[@wsu:Id]", wsucontext);
        if (wsuNodes != null && wsuNodes.getLength() != 0) {
            for (int i = 0; i < wsuNodes.getLength(); i++) {
                Element elem = (Element) wsuNodes.item(i);
                String id = elem.getAttributeNS(wsuNS, "Id");
                if (id != null && id.length() != 0) {
                    elem.setIdAttributeNS(wsuNS, "Id", true);
                }
            }
        }
        String certAlias = keystore.getCertificateAlias(cert);
        PrivateKey privateKey = (PrivateKey) keystore.getPrivateKey(certAlias);
        if (privateKey == null) {
            SAMLUtilsCommon.debug.error("private key is null");
            throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("nullprivatekey"));
        }
        if (algorithm == null || algorithm.length() == 0) {
            algorithm = getKeyAlgorithm(privateKey);
        }
        if (!isValidAlgorithm(algorithm)) {
            throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("invalidalgorithm"));
        }
        signature = new XMLSignature(doc, "", algorithm, Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
        root.appendChild(signature.getElement());
        int size = ids.size();
        for (int i = 0; i < size; ++i) {
            Transforms transforms = new Transforms(doc);
            transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
            String id = (String) ids.get(i);
            if (SAMLUtilsCommon.debug.messageEnabled()) {
                SAMLUtilsCommon.debug.message("id = " + id);
            }
            signature.addDocument("#" + id, transforms, Constants.ALGO_ID_DIGEST_SHA1);
        }
        KeyInfo keyInfo = signature.getKeyInfo();
        Element securityTokenRef = doc.createElementNS(wsseNS, SAMLConstants.TAG_SECURITYTOKENREFERENCE);
        keyInfo.addUnknownElement(securityTokenRef);
        securityTokenRef.setAttributeNS(SAMLConstants.NS_XMLNS, SAMLConstants.TAG_XMLNS, wsseNS);
        securityTokenRef.setAttributeNS(SAMLConstants.NS_XMLNS, SAMLConstants.TAG_XMLNS_SEC, SAMLConstants.NS_SEC);
        securityTokenRef.setAttributeNS(null, SAMLConstants.TAG_USAGE, SAMLConstants.TAG_SEC_MESSAGEAUTHENTICATION);
        Element reference = doc.createElementNS(wsseNS, SAMLConstants.TAG_REFERENCE);
        reference.setAttributeNS(null, SAMLConstants.TAG_URI, "#" + assertionID);
        securityTokenRef.appendChild(reference);
        signature.sign(privateKey);
    } catch (Exception e) {
        SAMLUtilsCommon.debug.error("signWithWSSX509TokenProfile " + "Exception: ", e);
        throw new XMLSignatureException(e.getMessage());
    }
    if (SAMLUtilsCommon.debug.messageEnabled()) {
        SAMLUtilsCommon.debug.message("SAML Signed doc = " + XMLUtils.print(doc.getDocumentElement()));
    }
    return signature.getElement();
}
Also used : KeyInfo(org.apache.xml.security.keys.KeyInfo) XMLSignature(org.apache.xml.security.signature.XMLSignature) Transforms(org.apache.xml.security.transforms.Transforms) TransformerException(javax.xml.transform.TransformerException)

Example 2 with Transforms

use of org.apache.xml.security.transforms.Transforms in project xades4j by luisgoncalves.

the class KeyInfoBuilder method buildKeyInfo.

void buildKeyInfo(X509Certificate signingCertificate, XMLSignature xmlSig) throws KeyingDataException, UnsupportedAlgorithmException {
    // Check key usage.
    // - KeyUsage[0] = digitalSignature
    // - KeyUsage[1] = nonRepudiation
    boolean[] keyUsage = signingCertificate.getKeyUsage();
    if (keyUsage != null && !keyUsage[0] && !keyUsage[1]) {
        throw new SigningCertKeyUsageException(signingCertificate);
    }
    try {
        signingCertificate.checkValidity();
    } catch (CertificateException ce) {
        // CertificateExpiredException or CertificateNotYetValidException
        throw new SigningCertValidityException(signingCertificate);
    }
    if (this.basicSignatureOptionsProvider.includeSigningCertificate()) {
        try {
            X509Data x509Data = new X509Data(xmlSig.getDocument());
            x509Data.addCertificate(signingCertificate);
            x509Data.addSubjectName(signingCertificate);
            x509Data.addIssuerSerial(signingCertificate.getIssuerX500Principal().getName(), signingCertificate.getSerialNumber());
            xmlSig.getKeyInfo().add(x509Data);
            if (this.basicSignatureOptionsProvider.signSigningCertificate()) {
                String keyInfoId = xmlSig.getId() + "-keyinfo";
                xmlSig.getKeyInfo().setId(keyInfoId);
                // Use same canonicalization URI as specified in the ds:CanonicalizationMethod for Signature.
                Algorithm canonAlg = this.algorithmsProvider.getCanonicalizationAlgorithmForSignature();
                CanonicalizerUtils.checkC14NAlgorithm(canonAlg);
                Transforms transforms = TransformUtils.createTransforms(canonAlg, this.algorithmsParametersMarshaller, xmlSig.getDocument());
                xmlSig.addDocument('#' + keyInfoId, transforms, this.algorithmsProvider.getDigestAlgorithmForDataObjsReferences());
            }
        } catch (XMLSignatureException ex) {
            throw new UnsupportedAlgorithmException("Digest algorithm not supported in the XML Signature provider", this.algorithmsProvider.getDigestAlgorithmForDataObjsReferences(), ex);
        } catch (XMLSecurityException ex) {
            throw new KeyingDataException(ex.getMessage(), ex);
        }
    }
    if (this.basicSignatureOptionsProvider.includePublicKey()) {
        xmlSig.addKeyInfo(signingCertificate.getPublicKey());
    }
}
Also used : Transforms(org.apache.xml.security.transforms.Transforms) UnsupportedAlgorithmException(xades4j.UnsupportedAlgorithmException) CertificateException(java.security.cert.CertificateException) X509Data(org.apache.xml.security.keys.content.X509Data) Algorithm(xades4j.algorithms.Algorithm) XMLSignatureException(org.apache.xml.security.signature.XMLSignatureException) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException)

Example 3 with Transforms

use of org.apache.xml.security.transforms.Transforms in project xades4j by luisgoncalves.

the class SignatureUtils method processReferences.

static ReferencesRes processReferences(XMLSignature signature) throws QualifyingPropertiesIncorporationException, XAdES4jXMLSigException {
    SignedInfo signedInfo = signature.getSignedInfo();
    List<RawDataObjectDesc> dataObjsReferences = new ArrayList<RawDataObjectDesc>(signedInfo.getLength() - 1);
    Reference signedPropsRef = null;
    for (int i = 0; i < signedInfo.getLength(); i++) {
        Reference ref;
        try {
            ref = signedInfo.item(i);
        } catch (XMLSecurityException ex) {
            throw new XAdES4jXMLSigException(String.format("Cannot process the %dth reference", i), ex);
        }
        String refTypeUri = ref.getType();
        // with its value set to: http://uri.etsi.org/01903#SignedProperties."
        if (QualifyingProperty.SIGNED_PROPS_TYPE_URI.equals(refTypeUri)) {
            if (signedPropsRef != null) {
                throw new QualifyingPropertiesIncorporationException("Multiple references to SignedProperties");
            }
            signedPropsRef = ref;
        } else {
            RawDataObjectDesc dataObj = new RawDataObjectDesc(ref);
            dataObjsReferences.add(dataObj);
            try {
                Transforms transfs = ref.getTransforms();
                if (transfs != null) {
                    for (int j = 0; j < transfs.getLength(); ++j) {
                        dataObj.withTransform(new GenericAlgorithm(transfs.item(j).getURI()));
                    }
                }
            } catch (XMLSecurityException ex) {
                throw new XAdES4jXMLSigException("Cannot process transfroms", ex);
            }
        }
    }
    if (null == signedPropsRef) // !!!
    // Still may be a XAdES signature, if the signing certificate is
    // protected. For now, that scenario is not supported.
    {
        throw new QualifyingPropertiesIncorporationException("SignedProperties reference not found");
    }
    return new ReferencesRes(dataObjsReferences, signedPropsRef);
}
Also used : Reference(org.apache.xml.security.signature.Reference) Transforms(org.apache.xml.security.transforms.Transforms) ArrayList(java.util.ArrayList) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException) GenericAlgorithm(xades4j.algorithms.GenericAlgorithm) SignedInfo(org.apache.xml.security.signature.SignedInfo) XAdES4jXMLSigException(xades4j.XAdES4jXMLSigException)

Example 4 with Transforms

use of org.apache.xml.security.transforms.Transforms in project santuario-java by apache.

the class RetrievalMethodResolver method resolveInput.

/**
 * Resolves the input from the given retrieval method
 * @return the input from the given retrieval method
 * @throws XMLSecurityException
 */
private static XMLSignatureInput resolveInput(RetrievalMethod rm, String baseURI, boolean secureValidation) throws XMLSecurityException {
    Attr uri = rm.getURIAttr();
    // Apply the transforms
    Transforms transforms = rm.getTransforms();
    ResourceResolver resRes = ResourceResolver.getInstance(uri, baseURI, secureValidation);
    XMLSignatureInput resource = resRes.resolve(uri, baseURI, secureValidation);
    if (transforms != null) {
        LOG.debug("We have Transforms");
        resource = transforms.performTransforms(resource);
    }
    return resource;
}
Also used : Transforms(org.apache.xml.security.transforms.Transforms) ResourceResolver(org.apache.xml.security.utils.resolver.ResourceResolver) XMLSignatureInput(org.apache.xml.security.signature.XMLSignatureInput) Attr(org.w3c.dom.Attr)

Example 5 with Transforms

use of org.apache.xml.security.transforms.Transforms in project santuario-java by apache.

the class SignedEncryptedTest method secureAndVerify.

public void secureAndVerify(TransformerFactory transformerFactory, boolean useDocumentSerializer) throws Exception {
    DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
    Document document = null;
    try (InputStream is = new ByteArrayInputStream(SAMPLE_MSG.getBytes(StandardCharsets.UTF_8))) {
        document = builder.parse(is);
    }
    // Set up the Key
    KeyPairGenerator rsaKeygen = KeyPairGenerator.getInstance("RSA");
    KeyPair kp = rsaKeygen.generateKeyPair();
    PrivateKey priv = kp.getPrivate();
    PublicKey pub = kp.getPublic();
    XMLSignature sig = new XMLSignature(document, "", XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1, Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
    Element sigElement = sig.getElement();
    document.getDocumentElement().appendChild(sigElement);
    XPathFactory xpf = XPathFactory.newInstance();
    XPath xpath = xpf.newXPath();
    xpath.setNamespaceContext(new DSNamespaceContext());
    Element element = (Element) xpath.evaluate("//*[local-name()='Body']", document, XPathConstants.NODE);
    String id = UUID.randomUUID().toString();
    element.setAttributeNS(null, "Id", id);
    element.setIdAttributeNS(null, "Id", true);
    Transforms transforms = new Transforms(document);
    transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
    sig.addDocument("#" + id, transforms, Constants.ALGO_ID_DIGEST_SHA1);
    sig.addKeyInfo(pub);
    sig.sign(priv);
    KeyGenerator keygen = KeyGenerator.getInstance("AES");
    keygen.init(256);
    SecretKey secretKey = keygen.generateKey();
    XMLCipher cipher = XMLCipher.getInstance(XMLCipher.AES_128);
    cipher.init(XMLCipher.ENCRYPT_MODE, secretKey);
    document = cipher.doFinal(document, element, true);
    XMLCipher deCipher = XMLCipher.getInstance(XMLCipher.AES_128);
    if (transformerFactory != null && deCipher.getSerializer() instanceof TransformSerializer) {
        Field f = deCipher.getSerializer().getClass().getDeclaredField("transformerFactory");
        f.setAccessible(true);
        f.set(deCipher.getSerializer(), transformerFactory);
    }
    if (useDocumentSerializer) {
        deCipher.setSerializer(new DocumentSerializer());
    }
    deCipher.init(XMLCipher.DECRYPT_MODE, secretKey);
    deCipher.doFinal(document, element, true);
    XMLSignature xmlSignatureVerifier = new XMLSignature(sigElement, "");
    Assert.assertTrue(xmlSignatureVerifier.checkSignatureValue(pub));
}
Also used : XPath(javax.xml.xpath.XPath) KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) PublicKey(java.security.PublicKey) Element(org.w3c.dom.Element) Transforms(org.apache.xml.security.transforms.Transforms) XMLCipher(org.apache.xml.security.encryption.XMLCipher) KeyPairGenerator(java.security.KeyPairGenerator) Document(org.w3c.dom.Document) TransformSerializer(org.apache.xml.security.encryption.TransformSerializer) XPathFactory(javax.xml.xpath.XPathFactory) Field(java.lang.reflect.Field) SecretKey(javax.crypto.SecretKey) DocumentBuilder(javax.xml.parsers.DocumentBuilder) ByteArrayInputStream(java.io.ByteArrayInputStream) XMLSignature(org.apache.xml.security.signature.XMLSignature) DSNamespaceContext(org.apache.xml.security.test.dom.DSNamespaceContext) DocumentSerializer(org.apache.xml.security.encryption.DocumentSerializer) KeyGenerator(javax.crypto.KeyGenerator)

Aggregations

Transforms (org.apache.xml.security.transforms.Transforms)43 XMLSignature (org.apache.xml.security.signature.XMLSignature)29 Element (org.w3c.dom.Element)23 Document (org.w3c.dom.Document)19 PrivateKey (java.security.PrivateKey)9 DocumentBuilder (javax.xml.parsers.DocumentBuilder)8 XPath (javax.xml.xpath.XPath)8 XPathFactory (javax.xml.xpath.XPathFactory)8 XMLSecurityException (org.apache.xml.security.exceptions.XMLSecurityException)8 InputStream (java.io.InputStream)7 DSNamespaceContext (org.apache.xml.security.test.dom.DSNamespaceContext)7 ByteArrayInputStream (java.io.ByteArrayInputStream)6 ByteArrayOutputStream (java.io.ByteArrayOutputStream)5 KeyStore (java.security.KeyStore)5 X509Certificate (java.security.cert.X509Certificate)5 TransformerException (javax.xml.transform.TransformerException)5 FileInputStream (java.io.FileInputStream)4 SignatureAlgorithm (org.apache.xml.security.algorithms.SignatureAlgorithm)4 ObjectContainer (org.apache.xml.security.signature.ObjectContainer)4 TransformationException (org.apache.xml.security.transforms.TransformationException)4