Search in sources :

Example 21 with Reference

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

the class EnvelopedSignatureFacet method preSign.

@Override
public void preSign(Document document, List<Reference> references, List<XMLObject> objects) throws XMLSignatureException {
    List<Transform> transforms = new ArrayList<Transform>();
    Transform envelopedTransform = newTransform(CanonicalizationMethod.ENVELOPED);
    transforms.add(envelopedTransform);
    Transform exclusiveTransform = newTransform(CanonicalizationMethod.EXCLUSIVE);
    transforms.add(exclusiveTransform);
    Reference reference = newReference("", transforms, null, null, null);
    references.add(reference);
}
Also used : Reference(javax.xml.crypto.dsig.Reference) ArrayList(java.util.ArrayList) Transform(javax.xml.crypto.dsig.Transform)

Example 22 with Reference

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

the class OOXMLSignatureFacet method addManifestReferences.

@SuppressWarnings("resource")
protected void addManifestReferences(List<Reference> manifestReferences) throws XMLSignatureException {
    OPCPackage ooxml = signatureConfig.getOpcPackage();
    List<PackagePart> relsEntryNames = ooxml.getPartsByContentType(ContentTypes.RELATIONSHIPS_PART);
    Set<String> digestedPartNames = new HashSet<String>();
    for (PackagePart pp : relsEntryNames) {
        String baseUri = pp.getPartName().getName().replaceFirst("(.*)/_rels/.*", "$1");
        PackageRelationshipCollection prc;
        try {
            prc = new PackageRelationshipCollection(ooxml);
            prc.parseRelationshipsPart(pp);
        } catch (InvalidFormatException e) {
            throw new XMLSignatureException("Invalid relationship descriptor: " + pp.getPartName().getName(), e);
        }
        RelationshipTransformParameterSpec parameterSpec = new RelationshipTransformParameterSpec();
        for (PackageRelationship relationship : prc) {
            String relationshipType = relationship.getRelationshipType();
            /*
                 * ECMA-376 Part 2 - 3rd edition
                 * 13.2.4.16 Manifest Element
                 * "The producer shall not create a Manifest element that references any data outside of the package."
                 */
            if (TargetMode.EXTERNAL == relationship.getTargetMode()) {
                continue;
            }
            if (!isSignedRelationship(relationshipType))
                continue;
            parameterSpec.addRelationshipReference(relationship.getId());
            // TODO: find a better way ...
            String partName = relationship.getTargetURI().toString();
            if (!partName.startsWith(baseUri)) {
                partName = baseUri + partName;
            }
            try {
                partName = new URI(partName).normalize().getPath().replace('\\', '/');
                LOG.log(POILogger.DEBUG, "part name: " + partName);
            } catch (URISyntaxException e) {
                throw new XMLSignatureException(e);
            }
            String contentType;
            try {
                PackagePartName relName = PackagingURIHelper.createPartName(partName);
                PackagePart pp2 = ooxml.getPart(relName);
                contentType = pp2.getContentType();
            } catch (InvalidFormatException e) {
                throw new XMLSignatureException(e);
            }
            if (relationshipType.endsWith("customXml") && !(contentType.equals("inkml+xml") || contentType.equals("text/xml"))) {
                LOG.log(POILogger.DEBUG, "skipping customXml with content type: " + contentType);
                continue;
            }
            if (!digestedPartNames.contains(partName)) {
                // We only digest a part once.
                String uri = partName + "?ContentType=" + contentType;
                Reference reference = newReference(uri, null, null, null, null);
                manifestReferences.add(reference);
                digestedPartNames.add(partName);
            }
        }
        if (parameterSpec.hasSourceIds()) {
            List<Transform> transforms = new ArrayList<Transform>();
            transforms.add(newTransform(RelationshipTransformService.TRANSFORM_URI, parameterSpec));
            transforms.add(newTransform(CanonicalizationMethod.INCLUSIVE));
            String uri = pp.getPartName().getName() + "?ContentType=application/vnd.openxmlformats-package.relationships+xml";
            Reference reference = newReference(uri, transforms, null, null, null);
            manifestReferences.add(reference);
        }
    }
}
Also used : PackagePartName(org.apache.poi.openxml4j.opc.PackagePartName) PackageRelationshipCollection(org.apache.poi.openxml4j.opc.PackageRelationshipCollection) Reference(javax.xml.crypto.dsig.Reference) ArrayList(java.util.ArrayList) URISyntaxException(java.net.URISyntaxException) PackagePart(org.apache.poi.openxml4j.opc.PackagePart) InvalidFormatException(org.apache.poi.openxml4j.exceptions.InvalidFormatException) URI(java.net.URI) PackageRelationship(org.apache.poi.openxml4j.opc.PackageRelationship) RelationshipTransformParameterSpec(org.apache.poi.poifs.crypt.dsig.services.RelationshipTransformService.RelationshipTransformParameterSpec) Transform(javax.xml.crypto.dsig.Transform) OPCPackage(org.apache.poi.openxml4j.opc.OPCPackage) XMLSignatureException(javax.xml.crypto.dsig.XMLSignatureException) HashSet(java.util.HashSet)

Example 23 with Reference

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

the class OOXMLSignatureFacet method addSignatureInfo.

protected void addSignatureInfo(Document document, List<Reference> references, List<XMLObject> objects) throws XMLSignatureException {
    List<XMLStructure> objectContent = new ArrayList<XMLStructure>();
    SignatureInfoV1Document sigV1 = SignatureInfoV1Document.Factory.newInstance();
    CTSignatureInfoV1 ctSigV1 = sigV1.addNewSignatureInfoV1();
    ctSigV1.setManifestHashAlgorithm(signatureConfig.getDigestMethodUri());
    Element n = (Element) document.importNode(ctSigV1.getDomNode(), true);
    n.setAttributeNS(XML_NS, XMLConstants.XMLNS_ATTRIBUTE, MS_DIGSIG_NS);
    List<XMLStructure> signatureInfoContent = new ArrayList<XMLStructure>();
    signatureInfoContent.add(new DOMStructure(n));
    SignatureProperty signatureInfoSignatureProperty = getSignatureFactory().newSignatureProperty(signatureInfoContent, "#" + signatureConfig.getPackageSignatureId(), "idOfficeV1Details");
    List<SignatureProperty> signaturePropertyContent = new ArrayList<SignatureProperty>();
    signaturePropertyContent.add(signatureInfoSignatureProperty);
    SignatureProperties signatureProperties = getSignatureFactory().newSignatureProperties(signaturePropertyContent, null);
    objectContent.add(signatureProperties);
    String objectId = "idOfficeObject";
    objects.add(getSignatureFactory().newXMLObject(objectContent, objectId, null, null));
    Reference reference = newReference("#" + objectId, null, XML_DIGSIG_NS + "Object", null, null);
    references.add(reference);
}
Also used : SignatureInfoV1Document(com.microsoft.schemas.office.x2006.digsig.SignatureInfoV1Document) Reference(javax.xml.crypto.dsig.Reference) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) DOMStructure(javax.xml.crypto.dom.DOMStructure) SignatureProperties(javax.xml.crypto.dsig.SignatureProperties) CTSignatureInfoV1(com.microsoft.schemas.office.x2006.digsig.CTSignatureInfoV1) XMLStructure(javax.xml.crypto.XMLStructure) SignatureProperty(javax.xml.crypto.dsig.SignatureProperty)

Example 24 with Reference

use of javax.xml.crypto.dsig.Reference 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)

Example 25 with Reference

use of javax.xml.crypto.dsig.Reference in project cxf by apache.

the class AbstractBindingBuilder method doSymmSignatureDerived.

private void doSymmSignatureDerived(AbstractToken policyToken, SecurityToken tok, List<WSEncryptionPart> sigParts, boolean isTokenProtection, boolean isSigProtect) throws WSSecurityException {
    Document doc = saaj.getSOAPPart();
    WSSecDKSign dkSign = new WSSecDKSign(secHeader);
    dkSign.setIdAllocator(wssConfig.getIdAllocator());
    dkSign.setCallbackLookup(callbackLookup);
    dkSign.setStoreBytesInAttachment(storeBytesInAttachment);
    dkSign.setExpandXopInclude(isExpandXopInclude());
    // Check whether it is security policy 1.2 and use the secure conversation accordingly
    if (policyToken.getVersion() == SPConstants.SPVersion.SP11) {
        dkSign.setWscVersion(ConversationConstants.VERSION_05_02);
    }
    // Check for whether the token is attached in the message or not
    boolean attached = false;
    if (isTokenRequired(policyToken.getIncludeTokenType())) {
        attached = true;
    }
    // Setting the AttachedReference or the UnattachedReference according to the flag
    Element ref;
    if (attached) {
        ref = tok.getAttachedReference();
    } else {
        ref = tok.getUnattachedReference();
    }
    if (ref != null) {
        ref = cloneElement(ref);
        dkSign.setExternalKey(tok.getSecret(), ref);
    } else if (!isRequestor() && policyToken.getDerivedKeys() == DerivedKeys.RequireDerivedKeys) {
        // If the Encrypted key used to create the derived key is not
        // attached use key identifier as defined in WSS1.1 section
        // 7.7 Encrypted Key reference
        SecurityTokenReference tokenRef = new SecurityTokenReference(doc);
        if (tok.getSHA1() != null) {
            tokenRef.setKeyIdentifierEncKeySHA1(tok.getSHA1());
            tokenRef.addTokenType(WSS4JConstants.WSS_ENC_KEY_VALUE_TYPE);
        }
        dkSign.setExternalKey(tok.getSecret(), tokenRef.getElement());
    } else {
        dkSign.setExternalKey(tok.getSecret(), tok.getId());
    }
    // Set the algo info
    dkSign.setSignatureAlgorithm(binding.getAlgorithmSuite().getSymmetricSignature());
    dkSign.setSigCanonicalization(binding.getAlgorithmSuite().getC14n().getValue());
    AlgorithmSuiteType algType = binding.getAlgorithmSuite().getAlgorithmSuiteType();
    dkSign.setDerivedKeyLength(algType.getSignatureDerivedKeyLength() / 8);
    if (tok.getSHA1() != null) {
        // Set the value type of the reference
        dkSign.setCustomValueType(WSS4JConstants.SOAPMESSAGE_NS11 + "#" + WSS4JConstants.ENC_KEY_VALUE_TYPE);
    } else if (policyToken instanceof UsernameToken) {
        dkSign.setCustomValueType(WSS4JConstants.WSS_USERNAME_TOKEN_VALUE_TYPE);
    }
    dkSign.prepare();
    if (isTokenProtection) {
        String sigTokId = XMLUtils.getIDFromReference(tok.getId());
        sigParts.add(new WSEncryptionPart(sigTokId));
    }
    dkSign.getParts().addAll(sigParts);
    List<Reference> referenceList = dkSign.addReferencesToSign(sigParts);
    // Add elements to header
    addSupportingElement(dkSign.getdktElement());
    // Do signature
    dkSign.computeSignature(referenceList, false, null);
    if (isSigProtect) {
        WSEncryptionPart part = new WSEncryptionPart(dkSign.getSignatureId(), "Element");
        encryptedTokensList.add(part);
    }
    addSig(dkSign.getSignatureValue());
}
Also used : WSSecDKSign(org.apache.wss4j.dom.message.WSSecDKSign) WSEncryptionPart(org.apache.wss4j.common.WSEncryptionPart) SecurityTokenReference(org.apache.wss4j.common.token.SecurityTokenReference) AlgorithmSuiteType(org.apache.wss4j.policy.model.AlgorithmSuite.AlgorithmSuiteType) Reference(javax.xml.crypto.dsig.Reference) SecurityTokenReference(org.apache.wss4j.common.token.SecurityTokenReference) Element(org.w3c.dom.Element) WSSecUsernameToken(org.apache.wss4j.dom.message.WSSecUsernameToken) UsernameToken(org.apache.wss4j.policy.model.UsernameToken) Document(org.w3c.dom.Document)

Aggregations

Reference (javax.xml.crypto.dsig.Reference)29 ArrayList (java.util.ArrayList)13 Element (org.w3c.dom.Element)12 XMLObject (javax.xml.crypto.dsig.XMLObject)10 Transform (javax.xml.crypto.dsig.Transform)8 SecurityTokenReference (org.apache.wss4j.common.token.SecurityTokenReference)8 AlgorithmSuiteType (org.apache.wss4j.policy.model.AlgorithmSuite.AlgorithmSuiteType)8 AttachmentCallbackHandler (org.apache.cxf.ws.security.wss4j.AttachmentCallbackHandler)7 WSEncryptionPart (org.apache.wss4j.common.WSEncryptionPart)7 WSSecUsernameToken (org.apache.wss4j.dom.message.WSSecUsernameToken)7 WSSecSignature (org.apache.wss4j.dom.message.WSSecSignature)6 UsernameToken (org.apache.wss4j.policy.model.UsernameToken)6 XMLStructure (javax.xml.crypto.XMLStructure)5 DOMStructure (javax.xml.crypto.dom.DOMStructure)5 SignedInfo (javax.xml.crypto.dsig.SignedInfo)5 XMLSignature (javax.xml.crypto.dsig.XMLSignature)5 XMLSignatureFactory (javax.xml.crypto.dsig.XMLSignatureFactory)5 DOMSignContext (javax.xml.crypto.dsig.dom.DOMSignContext)5 WSSecDKSign (org.apache.wss4j.dom.message.WSSecDKSign)5 Document (org.w3c.dom.Document)5