Search in sources :

Example 11 with XMLObject

use of javax.xml.crypto.dsig.XMLObject in project poi by apache.

the class SignatureInfo method preSign.

/**
     * Helper method for adding informations before the signing.
     * Normally {@link #confirmSignature()} is sufficient to be used.
     */
@SuppressWarnings("unchecked")
public DigestInfo preSign(Document document, List<DigestInfo> digestInfos) throws XMLSignatureException, MarshalException {
    signatureConfig.init(false);
    // it's necessary to explicitly set the mdssi namespace, but the sign() method has no
    // normal way to interfere with, so we need to add the namespace under the hand ...
    EventTarget target = (EventTarget) document;
    EventListener creationListener = signatureConfig.getSignatureMarshalListener();
    if (creationListener != null) {
        if (creationListener instanceof SignatureMarshalListener) {
            ((SignatureMarshalListener) creationListener).setEventTarget(target);
        }
        SignatureMarshalListener.setListener(target, creationListener, true);
    }
    /*
         * Signature context construction.
         */
    XMLSignContext xmlSignContext = new DOMSignContext(signatureConfig.getKey(), document);
    URIDereferencer uriDereferencer = signatureConfig.getUriDereferencer();
    if (null != uriDereferencer) {
        xmlSignContext.setURIDereferencer(uriDereferencer);
    }
    for (Map.Entry<String, String> me : signatureConfig.getNamespacePrefixes().entrySet()) {
        xmlSignContext.putNamespacePrefix(me.getKey(), me.getValue());
    }
    xmlSignContext.setDefaultNamespacePrefix("");
    // signatureConfig.getNamespacePrefixes().get(XML_DIGSIG_NS));
    brokenJvmWorkaround(xmlSignContext);
    XMLSignatureFactory signatureFactory = signatureConfig.getSignatureFactory();
    /*
         * Add ds:References that come from signing client local files.
         */
    List<Reference> references = new ArrayList<Reference>();
    for (DigestInfo digestInfo : safe(digestInfos)) {
        byte[] documentDigestValue = digestInfo.digestValue;
        String uri = new File(digestInfo.description).getName();
        Reference reference = SignatureFacet.newReference(uri, null, null, null, documentDigestValue, signatureConfig);
        references.add(reference);
    }
    /*
         * Invoke the signature facets.
         */
    List<XMLObject> objects = new ArrayList<XMLObject>();
    for (SignatureFacet signatureFacet : signatureConfig.getSignatureFacets()) {
        LOG.log(POILogger.DEBUG, "invoking signature facet: " + signatureFacet.getClass().getSimpleName());
        signatureFacet.preSign(document, references, objects);
    }
    /*
         * ds:SignedInfo
         */
    SignedInfo signedInfo;
    try {
        SignatureMethod signatureMethod = signatureFactory.newSignatureMethod(signatureConfig.getSignatureMethodUri(), null);
        CanonicalizationMethod canonicalizationMethod = signatureFactory.newCanonicalizationMethod(signatureConfig.getCanonicalizationMethod(), (C14NMethodParameterSpec) null);
        signedInfo = signatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod, references);
    } catch (GeneralSecurityException e) {
        throw new XMLSignatureException(e);
    }
    /*
         * JSR105 ds:Signature creation
         */
    String signatureValueId = signatureConfig.getPackageSignatureId() + "-signature-value";
    javax.xml.crypto.dsig.XMLSignature xmlSignature = signatureFactory.newXMLSignature(signedInfo, null, objects, signatureConfig.getPackageSignatureId(), signatureValueId);
    /*
         * ds:Signature Marshalling.
         */
    xmlSignature.sign(xmlSignContext);
    /*
         * Completion of undigested ds:References in the ds:Manifests.
         */
    for (XMLObject object : objects) {
        LOG.log(POILogger.DEBUG, "object java type: " + object.getClass().getName());
        List<XMLStructure> objectContentList = object.getContent();
        for (XMLStructure objectContent : objectContentList) {
            LOG.log(POILogger.DEBUG, "object content java type: " + objectContent.getClass().getName());
            if (!(objectContent instanceof Manifest))
                continue;
            Manifest manifest = (Manifest) objectContent;
            List<Reference> manifestReferences = manifest.getReferences();
            for (Reference manifestReference : manifestReferences) {
                if (manifestReference.getDigestValue() != null)
                    continue;
                DOMReference manifestDOMReference = (DOMReference) manifestReference;
                manifestDOMReference.digest(xmlSignContext);
            }
        }
    }
    /*
         * Completion of undigested ds:References.
         */
    List<Reference> signedInfoReferences = signedInfo.getReferences();
    for (Reference signedInfoReference : signedInfoReferences) {
        DOMReference domReference = (DOMReference) signedInfoReference;
        // ds:Reference with external digest value
        if (domReference.getDigestValue() != null)
            continue;
        domReference.digest(xmlSignContext);
    }
    /*
         * Calculation of XML signature digest value.
         */
    DOMSignedInfo domSignedInfo = (DOMSignedInfo) signedInfo;
    ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
    domSignedInfo.canonicalize(xmlSignContext, dataStream);
    byte[] octets = dataStream.toByteArray();
    /*
         * TODO: we could be using DigestOutputStream here to optimize memory
         * usage.
         */
    MessageDigest md = CryptoFunctions.getMessageDigest(signatureConfig.getDigestAlgo());
    byte[] digestValue = md.digest(octets);
    String description = signatureConfig.getSignatureDescription();
    return new DigestInfo(digestValue, signatureConfig.getDigestAlgo(), description);
}
Also used : ArrayList(java.util.ArrayList) XMLStructure(javax.xml.crypto.XMLStructure) URIDereferencer(javax.xml.crypto.URIDereferencer) XMLSignContext(javax.xml.crypto.dsig.XMLSignContext) EventListener(org.w3c.dom.events.EventListener) MessageDigest(java.security.MessageDigest) EventTarget(org.w3c.dom.events.EventTarget) XMLSignatureFactory(javax.xml.crypto.dsig.XMLSignatureFactory) DOMSignedInfo(org.apache.jcp.xml.dsig.internal.dom.DOMSignedInfo) DOMReference(org.apache.jcp.xml.dsig.internal.dom.DOMReference) Reference(javax.xml.crypto.dsig.Reference) GeneralSecurityException(java.security.GeneralSecurityException) CanonicalizationMethod(javax.xml.crypto.dsig.CanonicalizationMethod) XMLObject(javax.xml.crypto.dsig.XMLObject) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Manifest(javax.xml.crypto.dsig.Manifest) DOMReference(org.apache.jcp.xml.dsig.internal.dom.DOMReference) DOMSignedInfo(org.apache.jcp.xml.dsig.internal.dom.DOMSignedInfo) SignedInfo(javax.xml.crypto.dsig.SignedInfo) SignatureFacet(org.apache.poi.poifs.crypt.dsig.facets.SignatureFacet) DOMSignContext(javax.xml.crypto.dsig.dom.DOMSignContext) SignatureMethod(javax.xml.crypto.dsig.SignatureMethod) Map(java.util.Map) HashMap(java.util.HashMap) File(java.io.File) XMLSignatureException(javax.xml.crypto.dsig.XMLSignatureException) XMLSignature(javax.xml.crypto.dsig.XMLSignature)

Example 12 with XMLObject

use of javax.xml.crypto.dsig.XMLObject in project poi by apache.

the class XAdESSignatureFacet method preSign.

@Override
public void preSign(Document document, List<Reference> references, List<XMLObject> objects) throws XMLSignatureException {
    LOG.log(POILogger.DEBUG, "preSign");
    // QualifyingProperties
    QualifyingPropertiesDocument qualDoc = QualifyingPropertiesDocument.Factory.newInstance();
    QualifyingPropertiesType qualifyingProperties = qualDoc.addNewQualifyingProperties();
    qualifyingProperties.setTarget("#" + signatureConfig.getPackageSignatureId());
    // SignedProperties
    SignedPropertiesType signedProperties = qualifyingProperties.addNewSignedProperties();
    signedProperties.setId(signatureConfig.getXadesSignatureId());
    // SignedSignatureProperties
    SignedSignaturePropertiesType signedSignatureProperties = signedProperties.addNewSignedSignatureProperties();
    // SigningTime
    Calendar xmlGregorianCalendar = Calendar.getInstance(TimeZone.getTimeZone("Z"), Locale.ROOT);
    xmlGregorianCalendar.setTime(signatureConfig.getExecutionTime());
    xmlGregorianCalendar.clear(Calendar.MILLISECOND);
    signedSignatureProperties.setSigningTime(xmlGregorianCalendar);
    // SigningCertificate
    if (signatureConfig.getSigningCertificateChain() == null || signatureConfig.getSigningCertificateChain().isEmpty()) {
        throw new RuntimeException("no signing certificate chain available");
    }
    CertIDListType signingCertificates = signedSignatureProperties.addNewSigningCertificate();
    CertIDType certId = signingCertificates.addNewCert();
    X509Certificate certificate = signatureConfig.getSigningCertificateChain().get(0);
    setCertID(certId, signatureConfig, signatureConfig.isXadesIssuerNameNoReverseOrder(), certificate);
    // ClaimedRole
    String role = signatureConfig.getXadesRole();
    if (role != null && !role.isEmpty()) {
        SignerRoleType signerRole = signedSignatureProperties.addNewSignerRole();
        signedSignatureProperties.setSignerRole(signerRole);
        ClaimedRolesListType claimedRolesList = signerRole.addNewClaimedRoles();
        AnyType claimedRole = claimedRolesList.addNewClaimedRole();
        XmlString roleString = XmlString.Factory.newInstance();
        roleString.setStringValue(role);
        insertXChild(claimedRole, roleString);
    }
    // XAdES-EPES
    SignaturePolicyService policyService = signatureConfig.getSignaturePolicyService();
    if (policyService != null) {
        SignaturePolicyIdentifierType signaturePolicyIdentifier = signedSignatureProperties.addNewSignaturePolicyIdentifier();
        SignaturePolicyIdType signaturePolicyId = signaturePolicyIdentifier.addNewSignaturePolicyId();
        ObjectIdentifierType objectIdentifier = signaturePolicyId.addNewSigPolicyId();
        objectIdentifier.setDescription(policyService.getSignaturePolicyDescription());
        IdentifierType identifier = objectIdentifier.addNewIdentifier();
        identifier.setStringValue(policyService.getSignaturePolicyIdentifier());
        byte[] signaturePolicyDocumentData = policyService.getSignaturePolicyDocument();
        DigestAlgAndValueType sigPolicyHash = signaturePolicyId.addNewSigPolicyHash();
        setDigestAlgAndValue(sigPolicyHash, signaturePolicyDocumentData, signatureConfig.getDigestAlgo());
        String signaturePolicyDownloadUrl = policyService.getSignaturePolicyDownloadUrl();
        if (null != signaturePolicyDownloadUrl) {
            SigPolicyQualifiersListType sigPolicyQualifiers = signaturePolicyId.addNewSigPolicyQualifiers();
            AnyType sigPolicyQualifier = sigPolicyQualifiers.addNewSigPolicyQualifier();
            XmlString spUriElement = XmlString.Factory.newInstance();
            spUriElement.setStringValue(signaturePolicyDownloadUrl);
            insertXChild(sigPolicyQualifier, spUriElement);
        }
    } else if (signatureConfig.isXadesSignaturePolicyImplied()) {
        SignaturePolicyIdentifierType signaturePolicyIdentifier = signedSignatureProperties.addNewSignaturePolicyIdentifier();
        signaturePolicyIdentifier.addNewSignaturePolicyImplied();
    }
    // DataObjectFormat
    if (!dataObjectFormatMimeTypes.isEmpty()) {
        SignedDataObjectPropertiesType signedDataObjectProperties = signedProperties.addNewSignedDataObjectProperties();
        List<DataObjectFormatType> dataObjectFormats = signedDataObjectProperties.getDataObjectFormatList();
        for (Map.Entry<String, String> dataObjectFormatMimeType : this.dataObjectFormatMimeTypes.entrySet()) {
            DataObjectFormatType dataObjectFormat = DataObjectFormatType.Factory.newInstance();
            dataObjectFormat.setObjectReference("#" + dataObjectFormatMimeType.getKey());
            dataObjectFormat.setMimeType(dataObjectFormatMimeType.getValue());
            dataObjectFormats.add(dataObjectFormat);
        }
    }
    // add XAdES ds:Object
    List<XMLStructure> xadesObjectContent = new ArrayList<XMLStructure>();
    Element qualDocElSrc = (Element) qualifyingProperties.getDomNode();
    Element qualDocEl = (Element) document.importNode(qualDocElSrc, true);
    xadesObjectContent.add(new DOMStructure(qualDocEl));
    XMLObject xadesObject = getSignatureFactory().newXMLObject(xadesObjectContent, null, null, null);
    objects.add(xadesObject);
    // add XAdES ds:Reference
    List<Transform> transforms = new ArrayList<Transform>();
    Transform exclusiveTransform = newTransform(CanonicalizationMethod.INCLUSIVE);
    transforms.add(exclusiveTransform);
    Reference reference = newReference("#" + signatureConfig.getXadesSignatureId(), transforms, XADES_TYPE, null, null);
    references.add(reference);
}
Also used : SignaturePolicyIdentifierType(org.etsi.uri.x01903.v13.SignaturePolicyIdentifierType) SigPolicyQualifiersListType(org.etsi.uri.x01903.v13.SigPolicyQualifiersListType) QualifyingPropertiesDocument(org.etsi.uri.x01903.v13.QualifyingPropertiesDocument) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) XmlString(org.apache.xmlbeans.XmlString) XMLStructure(javax.xml.crypto.XMLStructure) DigestAlgAndValueType(org.etsi.uri.x01903.v13.DigestAlgAndValueType) SignedSignaturePropertiesType(org.etsi.uri.x01903.v13.SignedSignaturePropertiesType) DOMStructure(javax.xml.crypto.dom.DOMStructure) AnyType(org.etsi.uri.x01903.v13.AnyType) CertIDListType(org.etsi.uri.x01903.v13.CertIDListType) SignedPropertiesType(org.etsi.uri.x01903.v13.SignedPropertiesType) SignedDataObjectPropertiesType(org.etsi.uri.x01903.v13.SignedDataObjectPropertiesType) ClaimedRolesListType(org.etsi.uri.x01903.v13.ClaimedRolesListType) DataObjectFormatType(org.etsi.uri.x01903.v13.DataObjectFormatType) Reference(javax.xml.crypto.dsig.Reference) Calendar(java.util.Calendar) XmlString(org.apache.xmlbeans.XmlString) XMLObject(javax.xml.crypto.dsig.XMLObject) SignaturePolicyService(org.apache.poi.poifs.crypt.dsig.services.SignaturePolicyService) ObjectIdentifierType(org.etsi.uri.x01903.v13.ObjectIdentifierType) IdentifierType(org.etsi.uri.x01903.v13.IdentifierType) SignaturePolicyIdentifierType(org.etsi.uri.x01903.v13.SignaturePolicyIdentifierType) X509Certificate(java.security.cert.X509Certificate) CertIDType(org.etsi.uri.x01903.v13.CertIDType) QualifyingPropertiesType(org.etsi.uri.x01903.v13.QualifyingPropertiesType) SignerRoleType(org.etsi.uri.x01903.v13.SignerRoleType) ObjectIdentifierType(org.etsi.uri.x01903.v13.ObjectIdentifierType) SignaturePolicyIdType(org.etsi.uri.x01903.v13.SignaturePolicyIdType) Transform(javax.xml.crypto.dsig.Transform) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

XMLObject (javax.xml.crypto.dsig.XMLObject)12 Reference (javax.xml.crypto.dsig.Reference)10 ArrayList (java.util.ArrayList)8 XMLStructure (javax.xml.crypto.XMLStructure)5 DOMStructure (javax.xml.crypto.dom.DOMStructure)5 Manifest (javax.xml.crypto.dsig.Manifest)4 Transform (javax.xml.crypto.dsig.Transform)3 Document (org.w3c.dom.Document)3 Element (org.w3c.dom.Element)3 NodeList (org.w3c.dom.NodeList)3 HashMap (java.util.HashMap)2 List (java.util.List)2 Map (java.util.Map)2 XMLSignature (javax.xml.crypto.dsig.XMLSignature)2 XMLSignatureException (javax.xml.crypto.dsig.XMLSignatureException)2 XMLSignatureFactory (javax.xml.crypto.dsig.XMLSignatureFactory)2 Node (org.w3c.dom.Node)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 File (java.io.File)1