Search in sources :

Example 1 with XAdES4jXMLSigException

use of xades4j.XAdES4jXMLSigException in project xades4j by luisgoncalves.

the class XadesVerifierImpl method doCoreVerification.

private static void doCoreVerification(XMLSignature signature, SignatureSpecificVerificationOptions verificationOptions, X509Certificate validationCert) throws XAdES4jXMLSigException, InvalidSignatureException {
    List<ResourceResolver> resolvers = verificationOptions.getResolvers();
    if (!CollectionUtils.nullOrEmpty(resolvers)) {
        for (ResourceResolver resolver : resolvers) {
            signature.addResourceResolver(resolver);
        }
    }
    InputStream nullURIReferenceData = verificationOptions.getDataForAnonymousReference();
    if (nullURIReferenceData != null) {
        signature.addResourceResolver(new ResolverAnonymous(nullURIReferenceData));
    }
    try {
        if (signature.checkSignatureValue(validationCert)) {
            return;
        }
    } catch (XMLSignatureException ex) {
        throw new XAdES4jXMLSigException("Error verifying the signature", ex);
    }
    try {
        if (signature.getSignedInfo().verifyReferences()) // References are OK; this is a problem on the signature value
        // itself.
        {
            throw new SignatureValueException(signature);
        } else {
            // References are NOT OK; get the first invalid Reference.
            SignedInfo si = signature.getSignedInfo();
            for (int i = 0; i < si.getLength(); i++) {
                Reference r = si.item(i);
                if (!r.verify()) {
                    throw new ReferenceValueException(signature, r);
                }
            }
        }
    } catch (XMLSecurityException ex) {
        throw new XAdES4jXMLSigException("Error verifying the references", ex);
    }
}
Also used : XAdES4jXMLSigException(xades4j.XAdES4jXMLSigException) InputStream(java.io.InputStream) Reference(org.apache.xml.security.signature.Reference) ResourceResolver(org.apache.xml.security.utils.resolver.ResourceResolver) ResolverAnonymous(org.apache.xml.security.utils.resolver.implementations.ResolverAnonymous) XMLSignatureException(org.apache.xml.security.signature.XMLSignatureException) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException) SignedInfo(org.apache.xml.security.signature.SignedInfo)

Example 2 with XAdES4jXMLSigException

use of xades4j.XAdES4jXMLSigException 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 3 with XAdES4jXMLSigException

use of xades4j.XAdES4jXMLSigException in project xades4j by luisgoncalves.

the class SignerBES method createSignature.

private XMLSignature createSignature(Document signatureDocument, String baseUri, String signingKeyAlgorithm) throws XAdES4jXMLSigException, UnsupportedAlgorithmException {
    Algorithm signatureAlg = this.algorithmsProvider.getSignatureAlgorithm(signingKeyAlgorithm);
    if (null == signatureAlg) {
        throw new NullPointerException("Signature algorithm not provided");
    }
    Element signatureAlgElem = createElementForAlgorithm(signatureAlg, Constants._TAG_SIGNATUREMETHOD, signatureDocument);
    Algorithm canonAlg = this.algorithmsProvider.getCanonicalizationAlgorithmForSignature();
    if (null == canonAlg) {
        throw new NullPointerException("Canonicalization algorithm not provided");
    }
    Element canonAlgElem = createElementForAlgorithm(canonAlg, Constants._TAG_CANONICALIZATIONMETHOD, signatureDocument);
    try {
        return new XMLSignature(signatureDocument, baseUri, signatureAlgElem, canonAlgElem);
    } catch (XMLSecurityException ex) {
        // Following the code, doesn't seem to be thrown at all.
        throw new XAdES4jXMLSigException(ex.getMessage(), ex);
    }
}
Also used : XAdES4jXMLSigException(xades4j.XAdES4jXMLSigException) XMLSignature(org.apache.xml.security.signature.XMLSignature) Element(org.w3c.dom.Element) Algorithm(xades4j.algorithms.Algorithm) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException)

Example 4 with XAdES4jXMLSigException

use of xades4j.XAdES4jXMLSigException in project xades4j by luisgoncalves.

the class SignerBES method sign.

@Override
public final XadesSignatureResult sign(SignedDataObjects signedDataObjects, Node referenceNode, SignatureAppendingStrategy appendingStrategy) throws XAdES4jException {
    if (null == referenceNode) {
        throw new NullPointerException("Reference node node cannot be null");
    }
    if (null == signedDataObjects) {
        throw new NullPointerException("References cannot be null");
    }
    if (signedDataObjects.isEmpty()) {
        throw new IllegalArgumentException("Data objects list is empty");
    }
    Document signatureDocument = DOMHelper.getOwnerDocument(referenceNode);
    // Generate unique identifiers for the Signature and the SignedProperties.
    String signatureId = String.format("xmldsig-%s", UUID.randomUUID());
    String signedPropsId = String.format("%s-signedprops", signatureId);
    // Signing certificate chain (may contain only the signing certificate).
    List<X509Certificate> signingCertificateChain = this.keyingProvider.getSigningCertificateChain();
    if (null == signingCertificateChain || signingCertificateChain.isEmpty()) {
        throw new SigningCertChainException("Signing certificate not provided");
    }
    X509Certificate signingCertificate = signingCertificateChain.get(0);
    // The XMLSignature (ds:Signature).
    XMLSignature signature = createSignature(signatureDocument, signedDataObjects.getBaseUri(), signingCertificate.getPublicKey().getAlgorithm());
    signature.setId(signatureId);
    /* References */
    // Process the data object descriptions to get the References and mappings.
    // After this call all the signed data objects References and XMLObjects
    // are added to the signature.
    Map<DataObjectDesc, Reference> referenceMappings = this.dataObjectDescsProcessor.process(signedDataObjects, signature);
    /* ds:KeyInfo */
    this.keyInfoBuilder.buildKeyInfo(signingCertificate, signature);
    /* QualifyingProperties element */
    // Create the QualifyingProperties element
    Element qualifyingPropsElem = ElementProxy.createElementForFamily(signature.getDocument(), QualifyingProperty.XADES_XMLNS, QualifyingProperty.QUALIFYING_PROPS_TAG);
    qualifyingPropsElem.setAttributeNS(null, QualifyingProperty.TARGET_ATTR, '#' + signatureId);
    qualifyingPropsElem.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:xades141", QualifyingProperty.XADESV141_XMLNS);
    // ds:Object to contain QualifyingProperties
    ObjectContainer qPropsXmlObj = new ObjectContainer(signature.getDocument());
    qPropsXmlObj.appendChild(qualifyingPropsElem);
    try {
        signature.appendObject(qPropsXmlObj);
    } catch (XMLSignatureException ex) {
        // -> xmlSignature.appendObject(xmlObj): not thrown when signing.
        throw new IllegalStateException(ex);
    }
    /* Collect the properties */
    // Get the format specific signature properties.
    Collection<SignedSignatureProperty> fsssp = new ArrayList<SignedSignatureProperty>(2);
    Collection<UnsignedSignatureProperty> fsusp = new ArrayList<UnsignedSignatureProperty>(2);
    getFormatSpecificSignatureProperties(fsssp, fsusp, signingCertificateChain);
    // Gather all the signature and data objects properties.
    QualifyingProperties qualifProps = qualifPropsProcessor.getQualifyingProperties(signedDataObjects, fsssp, fsusp);
    try {
        // The signature needs to be appended to the document from now on because
        // property data generation may need to dereference same-document data
        // object references.
        appendingStrategy.append(signature.getElement(), referenceNode);
        /* Signed properties */
        // Create the context for signed properties data objects generation.
        PropertiesDataGenerationContext propsDataGenCtx = new PropertiesDataGenerationContext(signedDataObjects.getDataObjectsDescs(), referenceMappings, signatureDocument);
        // Generate the signed properties data objects. The data objects structure
        // is verifier in the process.
        SigAndDataObjsPropertiesData signedPropsData = this.propsDataObjectsGenerator.generateSignedPropertiesData(qualifProps.getSignedProperties(), propsDataGenCtx);
        // Marshal the signed properties data to the QualifyingProperties node.
        this.signedPropsMarshaller.marshal(signedPropsData, qualifyingPropsElem);
        Element signedPropsElem = DOMHelper.getFirstChildElement(qualifyingPropsElem);
        DOMHelper.setIdAsXmlId(signedPropsElem, signedPropsId);
        // SignedProperties reference
        // XAdES 6.3.1: "In order to protect the properties with the signature,
        // a ds:Reference element MUST be added to the XMLDSIG signature (...)
        // composed in such a way that it uses the SignedProperties element (...)
        // as the input for computing its corresponding digest. Additionally,
        // (...) use the Type attribute of this particular ds:Reference element,
        // with its value set to: http://uri.etsi.org/01903#SignedProperties."
        String digestAlgUri = algorithmsProvider.getDigestAlgorithmForDataObjsReferences();
        if (StringUtils.isNullOrEmptyString(digestAlgUri)) {
            throw new NullPointerException("Digest algorithm URI not provided");
        }
        // Use same canonicalization URI as specified in the ds:CanonicalizationMethod for Signature.
        Algorithm canonAlg = this.algorithmsProvider.getCanonicalizationAlgorithmForSignature();
        try {
            CanonicalizerUtils.checkC14NAlgorithm(canonAlg);
            Transforms transforms = TransformUtils.createTransforms(canonAlg, this.algorithmsParametersMarshaller, signatureDocument);
            signature.addDocument('#' + signedPropsId, transforms, digestAlgUri, null, QualifyingProperty.SIGNED_PROPS_TYPE_URI);
        } catch (XMLSignatureException ex) {
            // shouldn't be thrown now!
            throw new UnsupportedAlgorithmException("Digest algorithm not supported in the XML Signature provider", digestAlgUri, ex);
        }
        // Apply the signature
        try {
            PrivateKey signingKey = keyingProvider.getSigningKey(signingCertificate);
            signature.sign(signingKey);
        } catch (XMLSignatureException ex) {
            throw new XAdES4jXMLSigException(ex.getMessage(), ex);
        }
        // Set the ds:SignatureValue id.
        Element sigValueElem = DOMHelper.getFirstDescendant(signature.getElement(), Constants.SignatureSpecNS, Constants._TAG_SIGNATUREVALUE);
        DOMHelper.setIdAsXmlId(sigValueElem, String.format("%s-sigvalue", signatureId));
        /* Marshal unsigned properties */
        // Generate the unsigned properties data objects. The data objects structure
        // is verifier in the process.
        propsDataGenCtx.setTargetXmlSignature(signature);
        SigAndDataObjsPropertiesData unsignedPropsData = this.propsDataObjectsGenerator.generateUnsignedPropertiesData(qualifProps.getUnsignedProperties(), propsDataGenCtx);
        // Marshal the unsigned properties to the final QualifyingProperties node.
        this.unsignedPropsMarshaller.marshal(unsignedPropsData, qualifyingPropsElem);
    } catch (XAdES4jException ex) {
        appendingStrategy.revert(signature.getElement(), referenceNode);
        throw ex;
    }
    return new XadesSignatureResult(signature, qualifProps);
}
Also used : PrivateKey(java.security.PrivateKey) SigningCertChainException(xades4j.providers.SigningCertChainException) Element(org.w3c.dom.Element) Transforms(org.apache.xml.security.transforms.Transforms) ArrayList(java.util.ArrayList) Document(org.w3c.dom.Document) DataObjectDesc(xades4j.properties.DataObjectDesc) SigAndDataObjsPropertiesData(xades4j.properties.data.SigAndDataObjsPropertiesData) XAdES4jXMLSigException(xades4j.XAdES4jXMLSigException) XAdES4jException(xades4j.XAdES4jException) XMLSignature(org.apache.xml.security.signature.XMLSignature) Reference(org.apache.xml.security.signature.Reference) QualifyingProperties(xades4j.properties.QualifyingProperties) SignedSignatureProperty(xades4j.properties.SignedSignatureProperty) Algorithm(xades4j.algorithms.Algorithm) X509Certificate(java.security.cert.X509Certificate) UnsupportedAlgorithmException(xades4j.UnsupportedAlgorithmException) UnsignedSignatureProperty(xades4j.properties.UnsignedSignatureProperty) ObjectContainer(org.apache.xml.security.signature.ObjectContainer) XMLSignatureException(org.apache.xml.security.signature.XMLSignatureException)

Aggregations

XAdES4jXMLSigException (xades4j.XAdES4jXMLSigException)4 XMLSecurityException (org.apache.xml.security.exceptions.XMLSecurityException)3 Reference (org.apache.xml.security.signature.Reference)3 ArrayList (java.util.ArrayList)2 SignedInfo (org.apache.xml.security.signature.SignedInfo)2 XMLSignature (org.apache.xml.security.signature.XMLSignature)2 XMLSignatureException (org.apache.xml.security.signature.XMLSignatureException)2 Transforms (org.apache.xml.security.transforms.Transforms)2 Element (org.w3c.dom.Element)2 Algorithm (xades4j.algorithms.Algorithm)2 InputStream (java.io.InputStream)1 PrivateKey (java.security.PrivateKey)1 X509Certificate (java.security.cert.X509Certificate)1 ObjectContainer (org.apache.xml.security.signature.ObjectContainer)1 ResourceResolver (org.apache.xml.security.utils.resolver.ResourceResolver)1 ResolverAnonymous (org.apache.xml.security.utils.resolver.implementations.ResolverAnonymous)1 Document (org.w3c.dom.Document)1 UnsupportedAlgorithmException (xades4j.UnsupportedAlgorithmException)1 XAdES4jException (xades4j.XAdES4jException)1 GenericAlgorithm (xades4j.algorithms.GenericAlgorithm)1