Search in sources :

Example 1 with XAdES4jException

use of xades4j.XAdES4jException in project xades4j by luisgoncalves.

the class DefaultTimeStampVerificationProvider method verifyToken.

@Override
public Date verifyToken(byte[] timeStampToken, byte[] tsDigestInput) throws TimeStampTokenVerificationException {
    TimeStampToken tsToken;
    try {
        ASN1InputStream asn1is = new ASN1InputStream(timeStampToken);
        ContentInfo tsContentInfo = ContentInfo.getInstance(asn1is.readObject());
        asn1is.close();
        tsToken = new TimeStampToken(tsContentInfo);
    } catch (IOException ex) {
        throw new TimeStampTokenStructureException("Error parsing encoded token", ex);
    } catch (TSPException ex) {
        throw new TimeStampTokenStructureException("Invalid token", ex);
    }
    X509Certificate tsaCert = null;
    try {
        /* Validate the TSA certificate */
        LinkedList<X509Certificate> certs = new LinkedList<X509Certificate>();
        for (Object certHolder : tsToken.getCertificates().getMatches(new AllCertificatesSelector())) {
            certs.add(this.x509CertificateConverter.getCertificate((X509CertificateHolder) certHolder));
        }
        ValidationData vData = this.certificateValidationProvider.validate(x509CertSelectorConverter.getCertSelector(tsToken.getSID()), tsToken.getTimeStampInfo().getGenTime(), certs);
        tsaCert = vData.getCerts().get(0);
    } catch (CertificateException ex) {
        throw new TimeStampTokenVerificationException(ex.getMessage(), ex);
    } catch (XAdES4jException ex) {
        throw new TimeStampTokenTSACertException("cannot validate TSA certificate", ex);
    }
    try {
        tsToken.validate(this.signerInfoVerifierBuilder.build(tsaCert));
    } catch (TSPValidationException ex) {
        throw new TimeStampTokenSignatureException("Invalid token signature or certificate", ex);
    } catch (Exception ex) {
        throw new TimeStampTokenVerificationException("Error when verifying the token signature", ex);
    }
    org.bouncycastle.tsp.TimeStampTokenInfo tsTokenInfo = tsToken.getTimeStampInfo();
    try {
        String digestAlgUri = uriForDigest(tsTokenInfo.getMessageImprintAlgOID());
        MessageDigest md = messageDigestProvider.getEngine(digestAlgUri);
        if (!Arrays.equals(md.digest(tsDigestInput), tsTokenInfo.getMessageImprintDigest())) {
            throw new TimeStampTokenDigestException();
        }
    } catch (UnsupportedAlgorithmException ex) {
        throw new TimeStampTokenVerificationException("The token's digest algorithm is not supported", ex);
    }
    return tsTokenInfo.getGenTime();
}
Also used : CertificateException(java.security.cert.CertificateException) TimeStampTokenVerificationException(xades4j.providers.TimeStampTokenVerificationException) TimeStampTokenSignatureException(xades4j.providers.TimeStampTokenSignatureException) ContentInfo(org.bouncycastle.asn1.cms.ContentInfo) XAdES4jException(xades4j.XAdES4jException) TimeStampTokenDigestException(xades4j.providers.TimeStampTokenDigestException) MessageDigest(java.security.MessageDigest) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) TimeStampTokenStructureException(xades4j.providers.TimeStampTokenStructureException) TSPValidationException(org.bouncycastle.tsp.TSPValidationException) TimeStampTokenTSACertException(xades4j.providers.TimeStampTokenTSACertException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) LinkedList(java.util.LinkedList) TSPValidationException(org.bouncycastle.tsp.TSPValidationException) XAdES4jException(xades4j.XAdES4jException) TimeStampTokenTSACertException(xades4j.providers.TimeStampTokenTSACertException) TimeStampTokenStructureException(xades4j.providers.TimeStampTokenStructureException) TSPException(org.bouncycastle.tsp.TSPException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) UnsupportedAlgorithmException(xades4j.UnsupportedAlgorithmException) TimeStampTokenDigestException(xades4j.providers.TimeStampTokenDigestException) TimeStampTokenVerificationException(xades4j.providers.TimeStampTokenVerificationException) TimeStampTokenSignatureException(xades4j.providers.TimeStampTokenSignatureException) ValidationData(xades4j.providers.ValidationData) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) UnsupportedAlgorithmException(xades4j.UnsupportedAlgorithmException) TSPException(org.bouncycastle.tsp.TSPException) TimeStampToken(org.bouncycastle.tsp.TimeStampToken)

Example 2 with XAdES4jException

use of xades4j.XAdES4jException in project xades4j by luisgoncalves.

the class CounterSignatureVerifier method verify.

@Override
public QualifyingProperty verify(GenericDOMData propData, QualifyingPropertyVerificationContext ctx) throws InvalidPropertyException {
    XAdESVerificationResult res;
    try {
        Element sigElem = DOMHelper.getFirstChildElement(propData.getPropertyElement());
        res = verifier.verify(sigElem, null);
    } catch (XAdES4jException ex) {
        throw new CounterSignatureXadesVerificationException(ex);
    }
    // "Check that the enclosed signature correctly references the ds:SignatureValue
    // present in the countersigned XAdES signature."
    Node targetSigValueElem = ctx.getSignature().getElement().getElementsByTagNameNS(Constants.SignatureSpecNS, Constants._TAG_SIGNATUREVALUE).item(0);
    try {
        SignedInfo si = res.getXmlSignature().getSignedInfo();
        for (int i = 0; i < si.getLength(); i++) {
            Reference r = si.item(i);
            if (r.getContentsAfterTransformation().getSubNode() == targetSigValueElem)
                // The signature references the SignatureValue element.
                return new CounterSignatureProperty(res);
        }
        throw new CounterSignatureSigValueRefException();
    } catch (XMLSecurityException e) {
        // Shouldn't happen because the signature was already verified.
        throw new CounterSignatureVerificationException(e);
    }
}
Also used : XAdES4jException(xades4j.XAdES4jException) Reference(org.apache.xml.security.signature.Reference) CounterSignatureProperty(xades4j.properties.CounterSignatureProperty) Element(org.w3c.dom.Element) Node(org.w3c.dom.Node) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException) SignedInfo(org.apache.xml.security.signature.SignedInfo)

Example 3 with XAdES4jException

use of xades4j.XAdES4jException 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)

Example 4 with XAdES4jException

use of xades4j.XAdES4jException in project xades4j by luisgoncalves.

the class DataGenCounterSig method generatePropertyData.

/*
     * XAdES section 7.2.4.2:
     * "The content of this property is a XMLDSIG or XAdES signature whose ds:SignedInfo
     * MUST contain one ds:Reference element referencing the ds:SignatureValue element
     * of the embedding and countersigned XAdES signature. The content of the ds:DigestValue
     * in the aforementioned ds:Reference element of the countersignature MUST be the
     * base-64 encoded digest of the complete (and canonicalized) ds:SignatureValue
     * element (i.e. including the starting and closing tags) of the embedding and
     * countersigned XAdES signature."
     */
/* The ds:Reference element described above can be obtained with the default
     * XML-DSIG behaviour. We just need to reference the ds:SignatureValue element.
     */
@Override
public PropertyDataObject generatePropertyData(CounterSignatureProperty prop, PropertiesDataGenerationContext ctx) throws PropertyDataGenerationException {
    // The element has to be in the document tree for the references to be
    // resolved. UGLY WORKAROUND.
    Element qPs = DOMHelper.getFirstDescendant(ctx.getTargetXmlSignature().getElement(), QualifyingProperty.XADES_XMLNS, QualifyingProperty.QUALIFYING_PROPS_TAG);
    // Create the CounterSignature property element.
    Element counterSigElem = ctx.createElementInSignatureDoc("CounterSignature", qPs.getPrefix(), QualifyingProperty.XADES_XMLNS);
    qPs.appendChild(counterSigElem);
    try {
        // Rerence to the ds:SignatureValue element. This assumes that the
        // QualifyingProperties are in the signature's document and that the
        // SignatureValue element has an Id.
        Element sigValueElem = DOMHelper.getFirstDescendant(ctx.getTargetXmlSignature().getElement(), Constants.SignatureSpecNS, Constants._TAG_SIGNATUREVALUE);
        String sigValueId = sigValueElem.getAttribute(Constants._ATT_ID);
        DataObjectReference sigValueRef = new DataObjectReference('#' + sigValueId).withType(CounterSignatureProperty.COUNTER_SIGNATURE_TYPE_URI);
        XadesSigner counterSigner = prop.getCounterSigSigner();
        if (null == counterSigner)
            throw new PropertyDataGenerationException(prop, "signer not specified");
        try {
            SignedDataObjects objs = prop.getSignedDataObjectsForCounterSig();
            if (null == objs)
                objs = new SignedDataObjects();
            objs.withSignedDataObject(sigValueRef);
            counterSigner.sign(objs, counterSigElem);
        } catch (XAdES4jException ex) {
            throw new PropertyDataGenerationException(prop, "cannot apply counter signature", ex);
        }
    } finally {
        qPs.removeChild(counterSigElem);
    }
    return new GenericDOMData(counterSigElem);
}
Also used : XAdES4jException(xades4j.XAdES4jException) Element(org.w3c.dom.Element) GenericDOMData(xades4j.properties.data.GenericDOMData)

Example 5 with XAdES4jException

use of xades4j.XAdES4jException in project xades4j by luisgoncalves.

the class ValidationDataFromCertValidationProvider method getValidationData.

@Override
public ValidationData getValidationData(List<X509Certificate> certChainFragment) throws ValidationDataException {
    try {
        X509CertSelector cs = new X509CertSelector();
        cs.setCertificate(certChainFragment.get(0));
        return this.certificateValidationProvider.validate(cs, new Date(), certChainFragment);
    } catch (XAdES4jException ex) {
        throw new ValidationDataException("Cannot validate certificate to obtain validation data", ex);
    }
}
Also used : XAdES4jException(xades4j.XAdES4jException) X509CertSelector(java.security.cert.X509CertSelector) Date(java.util.Date)

Aggregations

XAdES4jException (xades4j.XAdES4jException)5 Element (org.w3c.dom.Element)3 X509Certificate (java.security.cert.X509Certificate)2 Reference (org.apache.xml.security.signature.Reference)2 UnsupportedAlgorithmException (xades4j.UnsupportedAlgorithmException)2 IOException (java.io.IOException)1 MessageDigest (java.security.MessageDigest)1 PrivateKey (java.security.PrivateKey)1 CertificateException (java.security.cert.CertificateException)1 X509CertSelector (java.security.cert.X509CertSelector)1 ArrayList (java.util.ArrayList)1 Date (java.util.Date)1 LinkedList (java.util.LinkedList)1 XMLSecurityException (org.apache.xml.security.exceptions.XMLSecurityException)1 ObjectContainer (org.apache.xml.security.signature.ObjectContainer)1 SignedInfo (org.apache.xml.security.signature.SignedInfo)1 XMLSignature (org.apache.xml.security.signature.XMLSignature)1 XMLSignatureException (org.apache.xml.security.signature.XMLSignatureException)1 Transforms (org.apache.xml.security.transforms.Transforms)1 ASN1InputStream (org.bouncycastle.asn1.ASN1InputStream)1