List of usage examples for javax.xml.crypto.dsig XMLSignatureFactory newTransform
public abstract Transform newTransform(String algorithm, XMLStructure params) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException;
Transform
for the specified algorithm URI and parameters. From source file:com.bcmcgroup.flare.xmldsig.Xmldsig.java
/** * Method used to create an enveloped digital signature for an element of a TAXII document. * * @param element the element to be signed * @param keyEntry the PrivateKeyEntry/*from w w w. j a va2 s. c o m*/ * @param cbIndex the index of the Content_Block if we're signing a Content_Block, otherwise set to -1 if we're signing the root element * @return the status of the operation * * Usage Example: * String pks = config.getProperty("pathToPublisherKeyStore"); * String pksPw = FLAREclientUtil.decrypt(config.getProperty("publisherKeyStorePassword")); * String keyName = config.getProperty("publisherKeyName"); * String keyPW = FLAREclientUtil.decrypt(config.getProperty("publisherKeyPassword")); * PrivateKeyEntry keyEntry = FLAREclientUtil.getKeyEntry(pks, pksPw, keyName, keyPW); * List<Integer> statusList = Xmldsig.sign(rootElement, keyEntry, -1); */ private static boolean sign(Element element, PrivateKeyEntry keyEntry, int cbIndex) { element.normalize(); boolean status = false; //Create XML Signature Factory XMLSignatureFactory xmlSigFactory = XMLSignatureFactory.getInstance("DOM"); PublicKey publicKey = ClientUtil.getPublicKey(keyEntry); PrivateKey privateKey = keyEntry.getPrivateKey(); DOMSignContext dsc = new DOMSignContext(privateKey, element); dsc.setDefaultNamespacePrefix("ds"); dsc.setURIDereferencer(new MyURIDereferencer(element)); SignedInfo si = null; DigestMethod dm = null; SignatureMethod sm = null; KeyInfo ki = null; X509Data xd; List<Serializable> x509Content = new ArrayList<>(); try { String algorithm = publicKey.getAlgorithm(); X509Certificate cert = (X509Certificate) keyEntry.getCertificate(); x509Content.add(cert.getSubjectX500Principal().getName()); x509Content.add(cert); String algorithmName = cert.getSigAlgName(); if (algorithm.toUpperCase().contains("RSA")) { if (algorithmName.toUpperCase().contains("SHA1")) { dm = xmlSigFactory.newDigestMethod(DigestMethod.SHA1, null); sm = xmlSigFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null); } else if (algorithmName.toUpperCase().contains("SHA2")) { dm = xmlSigFactory.newDigestMethod(DigestMethod.SHA256, null); sm = xmlSigFactory.newSignatureMethod(RSA_SHA256_URI, null); } else { logger.error("Error in digital signature application. " + algorithmName + " is not supported."); } CanonicalizationMethod cm; if (cbIndex != -1) { cm = xmlSigFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null); String refUri = "#xpointer(//*[local-name()='Content_Block'][" + cbIndex + "]/*[local-name()='Content'][1]/*)"; List<Reference> references = Collections.singletonList(xmlSigFactory.newReference(refUri, dm)); si = xmlSigFactory.newSignedInfo(cm, sm, references); } else { List<Transform> transforms = new ArrayList<>(2); transforms.add(xmlSigFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)); transforms.add(xmlSigFactory.newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null)); cm = xmlSigFactory.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null); String refUri = "#xpointer(/*)"; List<Reference> references = Collections .singletonList(xmlSigFactory.newReference(refUri, dm, transforms, null, null)); si = xmlSigFactory.newSignedInfo(cm, sm, references); } KeyInfoFactory kif = xmlSigFactory.getKeyInfoFactory(); xd = kif.newX509Data(x509Content); ki = kif.newKeyInfo(Collections.singletonList(xd)); } else { logger.error("Error in digital signature application. " + algorithmName + " is not supported."); } } catch (NoSuchAlgorithmException ex) { logger.error("NoSuchAlgorithm Exception when attempting to digitally sign a document."); } catch (InvalidAlgorithmParameterException ex) { logger.error("InvalidAlgorithmParameter Exception when attempting to digitally sign a document."); } // Create a new XML Signature XMLSignature signature = xmlSigFactory.newXMLSignature(si, ki); try { // Sign the document signature.sign(dsc); status = true; } catch (MarshalException ex) { logger.error("MarshalException when attempting to digitally sign a document."); } catch (XMLSignatureException ex) { logger.error("XMLSignature Exception when attempting to digitally sign a document."); } catch (Exception e) { logger.error("General exception when attempting to digitally sign a document."); } return status; }
From source file:eu.europa.ec.markt.dss.signature.xades.XAdESProfileBES.java
private DOMXMLSignature createEnveloping(SignatureParameters params, DOMSignContext signContext, org.w3c.dom.Document doc, String signatureId, String signatureValueId, Document inside) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, JAXBException, MarshalException, XMLSignatureException, ParserConfigurationException, IOException { XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI()); DigestMethod digestMethod = fac.newDigestMethod(params.getDigestAlgorithm().getXmlId(), null); List<XMLObject> objects = new ArrayList<XMLObject>(); List<Reference> references = new ArrayList<Reference>(); byte[] b64data = Base64.encode(IOUtils.toByteArray(inside.openStream())); List<Transform> transforms = new ArrayList<Transform>(); Map<String, String> xpathNamespaceMap = new HashMap<String, String>(); xpathNamespaceMap.put("ds", "http://www.w3.org/2000/09/xmldsig#"); Transform exclusiveTransform = fac.newTransform(CanonicalizationMethod.BASE64, (TransformParameterSpec) null); transforms.add(exclusiveTransform);// w w w . j a va 2s .c o m /* The first reference concern the whole document */ Reference reference = fac.newReference("#signed-data-" + computeDeterministicId(params), digestMethod, transforms, null, "signed-data-ref"); references.add(reference); String xadesSignedPropertiesId = "xades-" + computeDeterministicId(params); QualifyingPropertiesType qualifyingProperties = createXAdESQualifyingProperties(params, xadesSignedPropertiesId, reference, MimeType.PLAIN); qualifyingProperties.setTarget("#" + signatureId); Node marshallNode = doc.createElement("marshall-node"); JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.marshal(xades13ObjectFactory.createQualifyingProperties(qualifyingProperties), marshallNode); Element qualifier = (Element) marshallNode.getFirstChild(); // add XAdES ds:Object List<XMLStructure> xadesObjectContent = new LinkedList<XMLStructure>(); xadesObjectContent.add(new DOMStructure(marshallNode.getFirstChild())); XMLObject xadesObject = fac.newXMLObject(xadesObjectContent, null, null, null); objects.add(xadesObject); List<Transform> xadesTranforms = new ArrayList<Transform>(); Transform exclusiveTransform2 = fac.newTransform(CanonicalizationMethod.INCLUSIVE, (TransformParameterSpec) null); xadesTranforms.add(exclusiveTransform2); Reference xadesreference = fac.newReference("#" + xadesSignedPropertiesId, digestMethod, xadesTranforms, XADES_TYPE, null); references.add(xadesreference); /* Signed Info */ SignatureMethod sm = fac.newSignatureMethod( params.getSignatureAlgorithm().getXMLSignatureAlgorithm(params.getDigestAlgorithm()), null); CanonicalizationMethod canonicalizationMethod = fac .newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null); SignedInfo signedInfo = fac.newSignedInfo(canonicalizationMethod, sm, references); /* Creation of signature */ KeyInfoFactory keyFactory = KeyInfoFactory.getInstance("DOM", new XMLDSigRI()); List<Object> infos = new ArrayList<Object>(); List<X509Certificate> certs = new ArrayList<X509Certificate>(); certs.add(params.getSigningCertificate()); if (params.getCertificateChain() != null) { for (X509Certificate c : params.getCertificateChain()) { if (!c.getSubjectX500Principal().equals(params.getSigningCertificate().getSubjectX500Principal())) { certs.add(c); } } } infos.add(keyFactory.newX509Data(certs)); KeyInfo keyInfo = keyFactory.newKeyInfo(infos); DOMXMLSignature signature = (DOMXMLSignature) fac.newXMLSignature(signedInfo, keyInfo, objects, signatureId, signatureValueId); /* Marshall the signature to permit the digest. Need to be done before digesting the references. */ doc.removeChild(doc.getDocumentElement()); signature.marshal(doc, "ds", signContext); Element dsObject = doc.createElementNS(XMLSignature.XMLNS, "Object"); dsObject.setAttribute("Id", "signed-data-" + computeDeterministicId(params)); dsObject.setTextContent(new String(b64data)); doc.getDocumentElement().appendChild(dsObject); signContext.setIdAttributeNS((Element) qualifier.getFirstChild(), null, "Id"); signContext.setIdAttributeNS(dsObject, null, "Id"); digestReferences(signContext, references); return signature; }
From source file:be.fedict.eid.applet.service.signer.odf.ODFSignatureFacet.java
public void preSign(XMLSignatureFactory signatureFactory, Document document, String signatureId, List<X509Certificate> signingCertificateChain, List<Reference> references, List<XMLObject> objects) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { try {//from w w w.ja v a 2 s . c om URL odfUrl = this.signatureService.getOpenDocumentURL(); InputStream odfInputStream = odfUrl.openStream(); ZipInputStream odfZipInputStream = new ZipInputStream(odfInputStream); ZipEntry zipEntry; DigestMethod digestMethod = signatureFactory.newDigestMethod(this.digestAlgo.getXmlAlgoId(), null); while (null != (zipEntry = odfZipInputStream.getNextEntry())) { if (ODFUtil.isToBeSigned(zipEntry)) { String name = zipEntry.getName(); /* * Whitespaces are illegal in URIs * * Note that OOo 3.0/3.1 seems to have a bug, seems like the * OOo signature verification doesn't convert it back to * whitespace, to be investigated */ String uri = name.replaceAll(" ", "%20"); Reference reference; if (name.endsWith(".xml") && !isEmpty(odfZipInputStream)) { /* apply transformation on non-empty XML files only */ List<Transform> transforms = new LinkedList<Transform>(); Transform transform = signatureFactory.newTransform(CanonicalizationMethod.INCLUSIVE, (TransformParameterSpec) null); transforms.add(transform); reference = signatureFactory.newReference(uri, digestMethod, transforms, null, null); } else { reference = signatureFactory.newReference(uri, digestMethod); } references.add(reference); LOG.debug("entry: " + name); } } } catch (IOException e) { LOG.error("IO error: " + e.getMessage(), e); } catch (Exception e) { LOG.error("Error: " + e.getMessage(), e); } }
From source file:eu.europa.ec.markt.dss.signature.xades.XAdESProfileBES.java
private DOMXMLSignature createEnveloped(SignatureParameters params, DOMSignContext signContext, org.w3c.dom.Document doc, String signatureId, String signatureValueId) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, JAXBException, MarshalException, XMLSignatureException { XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI()); signContext.setURIDereferencer(new URIDereferencer() { @Override// w w w . j a v a 2 s . co m public Data dereference(URIReference uriReference, XMLCryptoContext context) throws URIReferenceException { final XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI()); Data data = fac.getURIDereferencer().dereference(uriReference, context); return data; } }); Map<String, String> xpathNamespaceMap = new HashMap<String, String>(); xpathNamespaceMap.put("ds", XMLSignature.XMLNS); List<Reference> references = new ArrayList<Reference>(); /* The first reference concern the whole document */ List<Transform> transforms = new ArrayList<Transform>(); transforms.add(fac.newTransform(CanonicalizationMethod.ENVELOPED, (TransformParameterSpec) null)); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); org.w3c.dom.Document empty; try { empty = dbf.newDocumentBuilder().newDocument(); } catch (ParserConfigurationException e1) { throw new RuntimeException(e1); } Element xpathEl = empty.createElementNS(XMLSignature.XMLNS, "XPath"); xpathEl.setTextContent(""); empty.adoptNode(xpathEl); XPathFilterParameterSpec specs = new XPathFilterParameterSpec("not(ancestor-or-self::ds:Signature)"); DOMTransform t = (DOMTransform) fac.newTransform("http://www.w3.org/TR/1999/REC-xpath-19991116", specs); transforms.add(t); DigestMethod digestMethod = fac.newDigestMethod(params.getDigestAlgorithm().getXmlId(), null); Reference reference = fac.newReference("", digestMethod, transforms, null, "xml_ref_id"); references.add(reference); List<XMLObject> objects = new ArrayList<XMLObject>(); String xadesSignedPropertiesId = "xades-" + computeDeterministicId(params); QualifyingPropertiesType qualifyingProperties = createXAdESQualifyingProperties(params, xadesSignedPropertiesId, reference, MimeType.XML); qualifyingProperties.setTarget("#" + signatureId); Node marshallNode = doc.createElement("marshall-node"); JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.marshal(xades13ObjectFactory.createQualifyingProperties(qualifyingProperties), marshallNode); Element qualifier = (Element) marshallNode.getFirstChild(); // add XAdES ds:Object List<XMLStructure> xadesObjectContent = new LinkedList<XMLStructure>(); xadesObjectContent.add(new DOMStructure(marshallNode.getFirstChild())); XMLObject xadesObject = fac.newXMLObject(xadesObjectContent, null, null, null); objects.add(xadesObject); Reference xadesreference = fac.newReference("#" + xadesSignedPropertiesId, digestMethod, Collections.singletonList( fac.newTransform(CanonicalizationMethod.INCLUSIVE, (TransformParameterSpec) null)), XADES_TYPE, null); references.add(xadesreference); /* Signed Info */ SignatureMethod sm = fac.newSignatureMethod( params.getSignatureAlgorithm().getXMLSignatureAlgorithm(params.getDigestAlgorithm()), null); CanonicalizationMethod canonicalizationMethod = fac .newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null); SignedInfo signedInfo = fac.newSignedInfo(canonicalizationMethod, sm, references); /* Creation of signature */ KeyInfoFactory keyFactory = KeyInfoFactory.getInstance("DOM", new XMLDSigRI()); List<Object> infos = new ArrayList<Object>(); List<X509Certificate> certs = new ArrayList<X509Certificate>(); certs.add(params.getSigningCertificate()); if (params.getCertificateChain() != null) { for (X509Certificate c : params.getCertificateChain()) { if (!c.getSubjectX500Principal().equals(params.getSigningCertificate().getSubjectX500Principal())) { certs.add(c); } } } infos.add(keyFactory.newX509Data(certs)); KeyInfo keyInfo = keyFactory.newKeyInfo(infos); DOMXMLSignature signature = (DOMXMLSignature) fac.newXMLSignature(signedInfo, keyInfo, objects, signatureId, signatureValueId); /* Marshall the signature to permit the digest. Need to be done before digesting the references. */ signature.marshal(doc.getDocumentElement(), "ds", signContext); signContext.setIdAttributeNS((Element) qualifier.getFirstChild(), null, "Id"); digestReferences(signContext, references); return signature; }
From source file:be.fedict.eid.tsl.TrustServiceList.java
private void xmlSign(PrivateKey privateKey, X509Certificate certificate, String tslId) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException, XMLSignatureException {//from ww w . j a v a2 s. c o m XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM", new org.jcp.xml.dsig.internal.dom.XMLDSigRI()); LOG.debug("xml signature factory: " + signatureFactory.getClass().getName()); LOG.debug("loader: " + signatureFactory.getClass().getClassLoader()); XMLSignContext signContext = new DOMSignContext(privateKey, this.tslDocument.getDocumentElement()); signContext.putNamespacePrefix(XMLSignature.XMLNS, "ds"); DigestMethod digestMethod = signatureFactory.newDigestMethod(DigestMethod.SHA256, null); List<Reference> references = new LinkedList<Reference>(); List<Transform> transforms = new LinkedList<Transform>(); transforms.add(signatureFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)); Transform exclusiveTransform = signatureFactory.newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null); transforms.add(exclusiveTransform); Reference reference = signatureFactory.newReference("#" + tslId, digestMethod, transforms, null, null); references.add(reference); String signatureId = "xmldsig-" + UUID.randomUUID().toString(); List<XMLObject> objects = new LinkedList<XMLObject>(); addXadesBes(signatureFactory, this.tslDocument, signatureId, certificate, references, objects); SignatureMethod signatureMethod; if (isJava6u18OrAbove()) { signatureMethod = signatureFactory .newSignatureMethod("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", null); } else { signatureMethod = signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null); } CanonicalizationMethod canonicalizationMethod = signatureFactory .newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null); SignedInfo signedInfo = signatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod, references); List<Object> keyInfoContent = new LinkedList<Object>(); KeyInfoFactory keyInfoFactory = KeyInfoFactory.getInstance(); List<Object> x509DataObjects = new LinkedList<Object>(); x509DataObjects.add(certificate); x509DataObjects.add(keyInfoFactory.newX509IssuerSerial(certificate.getIssuerX500Principal().toString(), certificate.getSerialNumber())); X509Data x509Data = keyInfoFactory.newX509Data(x509DataObjects); keyInfoContent.add(x509Data); KeyValue keyValue; try { keyValue = keyInfoFactory.newKeyValue(certificate.getPublicKey()); } catch (KeyException e) { throw new RuntimeException("key exception: " + e.getMessage(), e); } keyInfoContent.add(keyValue); KeyInfo keyInfo = keyInfoFactory.newKeyInfo(keyInfoContent); String signatureValueId = signatureId + "-signature-value"; XMLSignature xmlSignature = signatureFactory.newXMLSignature(signedInfo, keyInfo, objects, signatureId, signatureValueId); xmlSignature.sign(signContext); }
From source file:eu.europa.ec.markt.dss.signature.xades.XAdESProfileBES.java
private DOMXMLSignature createDetached(SignatureParameters params, DOMSignContext signContext, org.w3c.dom.Document doc, String signatureId, String signatureValueId, final Document inside) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, JAXBException, MarshalException, XMLSignatureException, ParserConfigurationException, IOException { final XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI()); DigestMethod digestMethod = fac.newDigestMethod(params.getDigestAlgorithm().getXmlId(), null); // Create references List<Reference> references = new ArrayList<Reference>(); addReferences(documentIterator(inside), references, digestMethod, fac); // Create repository signContext.setURIDereferencer(new NameBasedDocumentRepository(inside, fac)); List<XMLObject> objects = new ArrayList<XMLObject>(); Map<String, String> xpathNamespaceMap = new HashMap<String, String>(); xpathNamespaceMap.put("ds", "http://www.w3.org/2000/09/xmldsig#"); String xadesSignedPropertiesId = "xades-" + computeDeterministicId(params); QualifyingPropertiesType qualifyingProperties = createXAdESQualifyingProperties(params, xadesSignedPropertiesId, references, inside); qualifyingProperties.setTarget("#" + signatureId); Node marshallNode = doc.createElement("marshall-node"); JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.marshal(xades13ObjectFactory.createQualifyingProperties(qualifyingProperties), marshallNode); Element qualifier = (Element) marshallNode.getFirstChild(); // add XAdES ds:Object List<XMLStructure> xadesObjectContent = new LinkedList<XMLStructure>(); xadesObjectContent.add(new DOMStructure(marshallNode.getFirstChild())); XMLObject xadesObject = fac.newXMLObject(xadesObjectContent, null, null, null); objects.add(xadesObject);/* www . j ava 2 s. c o m*/ List<Transform> xadesTranforms = new ArrayList<Transform>(); Transform exclusiveTransform2 = fac.newTransform(CanonicalizationMethod.INCLUSIVE, (TransformParameterSpec) null); xadesTranforms.add(exclusiveTransform2); Reference xadesreference = fac.newReference("#" + xadesSignedPropertiesId, digestMethod, xadesTranforms, XADES_TYPE, null); references.add(xadesreference); /* Signed Info */ SignatureMethod sm = fac.newSignatureMethod( params.getSignatureAlgorithm().getXMLSignatureAlgorithm(params.getDigestAlgorithm()), null); CanonicalizationMethod canonicalizationMethod = fac .newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null); SignedInfo signedInfo = fac.newSignedInfo(canonicalizationMethod, sm, references); /* Creation of signature */ KeyInfoFactory keyFactory = KeyInfoFactory.getInstance("DOM", new XMLDSigRI()); List<Object> infos = new ArrayList<Object>(); List<X509Certificate> certs = new ArrayList<X509Certificate>(); certs.add(params.getSigningCertificate()); if (params.getCertificateChain() != null) { for (X509Certificate c : params.getCertificateChain()) { if (!c.getSubjectX500Principal().equals(params.getSigningCertificate().getSubjectX500Principal())) { certs.add(c); } } } infos.add(keyFactory.newX509Data(certs)); KeyInfo keyInfo = keyFactory.newKeyInfo(infos); DOMXMLSignature signature = (DOMXMLSignature) fac.newXMLSignature(signedInfo, keyInfo, objects, signatureId, signatureValueId); /* Marshall the signature to permit the digest. Need to be done before digesting the references. */ doc.removeChild(doc.getDocumentElement()); signature.marshal(doc, "ds", signContext); signContext.setIdAttributeNS((Element) qualifier.getFirstChild(), null, "Id"); digestReferences(signContext, references); return signature; }
From source file:be.fedict.eid.applet.service.signer.ooxml.OOXMLSignatureFacet.java
private void addManifestReferences(XMLSignatureFactory signatureFactory, Document document, List<Reference> manifestReferences) throws IOException, JAXBException, NoSuchAlgorithmException, InvalidAlgorithmParameterException { CTTypes contentTypes = getContentTypes(); List<String> relsEntryNames = getRelsEntryNames(); DigestMethod digestMethod = signatureFactory.newDigestMethod(this.digestAlgo.getXmlAlgoId(), null); Set<String> digestedPartNames = new HashSet<String>(); for (String relsEntryName : relsEntryNames) { CTRelationships relationships = getRelationships(relsEntryName); List<CTRelationship> relationshipList = relationships.getRelationship(); RelationshipTransformParameterSpec parameterSpec = new RelationshipTransformParameterSpec(); for (CTRelationship relationship : relationshipList) { String relationshipType = relationship.getType(); STTargetMode targetMode = relationship.getTargetMode(); if (null != targetMode) { LOG.debug("TargetMode: " + targetMode.name()); if (targetMode == STTargetMode.EXTERNAL) { /*//from ww w. ja v a2 s.c om * 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." */ continue; } } if (false == OOXMLSignatureFacet.isSignedRelationship(relationshipType)) { continue; } String baseUri = "/" + relsEntryName.substring(0, relsEntryName.indexOf("_rels/")); String relationshipTarget = relationship.getTarget(); String partName = FilenameUtils .separatorsToUnix(FilenameUtils.normalize(baseUri + relationshipTarget)); LOG.debug("part name: " + partName); String relationshipId = relationship.getId(); parameterSpec.addRelationshipReference(relationshipId); String contentType = getContentType(contentTypes, partName); if (relationshipType.endsWith("customXml")) { if (false == contentType.equals("inkml+xml") && false == contentType.equals("text/xml")) { LOG.debug("skipping customXml with content type: " + contentType); continue; } } if (false == digestedPartNames.contains(partName)) { /* * We only digest a part once. */ Reference reference = signatureFactory.newReference(partName + "?ContentType=" + contentType, digestMethod); manifestReferences.add(reference); digestedPartNames.add(partName); } } if (false == parameterSpec.getSourceIds().isEmpty()) { List<Transform> transforms = new LinkedList<Transform>(); transforms.add( signatureFactory.newTransform(RelationshipTransformService.TRANSFORM_URI, parameterSpec)); transforms.add(signatureFactory.newTransform(CanonicalizationMethod.INCLUSIVE, (TransformParameterSpec) null)); Reference reference = signatureFactory.newReference( "/" + relsEntryName + "?ContentType=application/vnd.openxmlformats-package.relationships+xml", digestMethod, transforms, null, null); manifestReferences.add(reference); } } }
From source file:be.fedict.eid.tsl.TrustServiceList.java
public void addXadesBes(XMLSignatureFactory signatureFactory, Document document, String signatureId, X509Certificate signingCertificate, List<Reference> references, List<XMLObject> objects) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { LOG.debug("preSign"); // QualifyingProperties QualifyingPropertiesType qualifyingProperties = this.xadesObjectFactory.createQualifyingPropertiesType(); qualifyingProperties.setTarget("#" + signatureId); // SignedProperties SignedPropertiesType signedProperties = this.xadesObjectFactory.createSignedPropertiesType(); String signedPropertiesId = signatureId + "-xades"; signedProperties.setId(signedPropertiesId); qualifyingProperties.setSignedProperties(signedProperties); // SignedSignatureProperties SignedSignaturePropertiesType signedSignatureProperties = this.xadesObjectFactory .createSignedSignaturePropertiesType(); signedProperties.setSignedSignatureProperties(signedSignatureProperties); // SigningTime GregorianCalendar signingTime = new GregorianCalendar(); signingTime.setTimeZone(TimeZone.getTimeZone("Z")); XMLGregorianCalendar xmlSigningTime = this.datatypeFactory.newXMLGregorianCalendar(signingTime); xmlSigningTime.setMillisecond(DatatypeConstants.FIELD_UNDEFINED); signedSignatureProperties.setSigningTime(xmlSigningTime); // SigningCertificate CertIDListType signingCertificates = this.xadesObjectFactory.createCertIDListType(); CertIDType signingCertificateId = this.xadesObjectFactory.createCertIDType(); X509IssuerSerialType issuerSerial = this.xmldsigObjectFactory.createX509IssuerSerialType(); issuerSerial.setX509IssuerName(signingCertificate.getIssuerX500Principal().toString()); issuerSerial.setX509SerialNumber(signingCertificate.getSerialNumber()); signingCertificateId.setIssuerSerial(issuerSerial); DigestAlgAndValueType certDigest = this.xadesObjectFactory.createDigestAlgAndValueType(); DigestMethodType jaxbDigestMethod = this.xmldsigObjectFactory.createDigestMethodType(); jaxbDigestMethod.setAlgorithm(DigestMethod.SHA256); certDigest.setDigestMethod(jaxbDigestMethod); MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); byte[] digestValue; try {// w w w . j a va2 s . co m digestValue = messageDigest.digest(signingCertificate.getEncoded()); } catch (CertificateEncodingException e) { throw new RuntimeException("certificate encoding error: " + e.getMessage(), e); } certDigest.setDigestValue(digestValue); signingCertificateId.setCertDigest(certDigest); signingCertificates.getCert().add(signingCertificateId); signedSignatureProperties.setSigningCertificate(signingCertificates); // marshall XAdES QualifyingProperties Node qualifyingPropertiesNode = marshallQualifyingProperties(document, qualifyingProperties); // add XAdES ds:Object List<XMLStructure> xadesObjectContent = new LinkedList<XMLStructure>(); xadesObjectContent.add(new DOMStructure(qualifyingPropertiesNode)); XMLObject xadesObject = signatureFactory.newXMLObject(xadesObjectContent, null, null, null); objects.add(xadesObject); // add XAdES ds:Reference DigestMethod digestMethod = signatureFactory.newDigestMethod(DigestMethod.SHA256, null); List<Transform> transforms = new LinkedList<Transform>(); Transform exclusiveTransform = signatureFactory.newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null); transforms.add(exclusiveTransform); Reference reference = signatureFactory.newReference("#" + signedPropertiesId, digestMethod, transforms, XADES_TYPE, null); references.add(reference); }
From source file:be.fedict.eid.applet.service.signer.facets.XAdESSignatureFacet.java
public void preSign(XMLSignatureFactory signatureFactory, Document document, String signatureId, List<X509Certificate> signingCertificateChain, List<Reference> references, List<XMLObject> objects) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { LOG.debug("preSign"); // QualifyingProperties QualifyingPropertiesType qualifyingProperties = this.xadesObjectFactory.createQualifyingPropertiesType(); qualifyingProperties.setTarget("#" + signatureId); // SignedProperties SignedPropertiesType signedProperties = this.xadesObjectFactory.createSignedPropertiesType(); String signedPropertiesId;//from w ww .j a v a 2 s .c o m if (null != this.idSignedProperties) { signedPropertiesId = this.idSignedProperties; } else { signedPropertiesId = signatureId + "-xades"; } signedProperties.setId(signedPropertiesId); qualifyingProperties.setSignedProperties(signedProperties); // SignedSignatureProperties SignedSignaturePropertiesType signedSignatureProperties = this.xadesObjectFactory .createSignedSignaturePropertiesType(); signedProperties.setSignedSignatureProperties(signedSignatureProperties); // SigningTime GregorianCalendar signingTime = new GregorianCalendar(TimeZone.getTimeZone("Z")); Date currentClockValue = this.clock.getTime(); signingTime.setTime(currentClockValue); XMLGregorianCalendar xmlGregorianCalendar = this.datatypeFactory.newXMLGregorianCalendar(signingTime); xmlGregorianCalendar.setMillisecond(DatatypeConstants.FIELD_UNDEFINED); signedSignatureProperties.setSigningTime(xmlGregorianCalendar); // SigningCertificate if (null == signingCertificateChain || signingCertificateChain.isEmpty()) { throw new RuntimeException("no signing certificate chain available"); } X509Certificate signingCertificate = signingCertificateChain.get(0); CertIDType signingCertificateId = getCertID(signingCertificate, this.xadesObjectFactory, this.xmldsigObjectFactory, this.digestAlgorithm, this.issuerNameNoReverseOrder); CertIDListType signingCertificates = this.xadesObjectFactory.createCertIDListType(); signingCertificates.getCert().add(signingCertificateId); signedSignatureProperties.setSigningCertificate(signingCertificates); // ClaimedRole if (null != this.role && false == this.role.isEmpty()) { SignerRoleType signerRole = this.xadesObjectFactory.createSignerRoleType(); signedSignatureProperties.setSignerRole(signerRole); ClaimedRolesListType claimedRolesList = this.xadesObjectFactory.createClaimedRolesListType(); signerRole.setClaimedRoles(claimedRolesList); AnyType claimedRole = this.xadesObjectFactory.createAnyType(); claimedRole.getContent().add(this.role); claimedRolesList.getClaimedRole().add(claimedRole); } // XAdES-EPES if (null != this.signaturePolicyService) { SignaturePolicyIdentifierType signaturePolicyIdentifier = this.xadesObjectFactory .createSignaturePolicyIdentifierType(); signedSignatureProperties.setSignaturePolicyIdentifier(signaturePolicyIdentifier); SignaturePolicyIdType signaturePolicyId = this.xadesObjectFactory.createSignaturePolicyIdType(); signaturePolicyIdentifier.setSignaturePolicyId(signaturePolicyId); ObjectIdentifierType objectIdentifier = this.xadesObjectFactory.createObjectIdentifierType(); signaturePolicyId.setSigPolicyId(objectIdentifier); IdentifierType identifier = this.xadesObjectFactory.createIdentifierType(); objectIdentifier.setIdentifier(identifier); identifier.setValue(this.signaturePolicyService.getSignaturePolicyIdentifier()); objectIdentifier.setDescription(this.signaturePolicyService.getSignaturePolicyDescription()); byte[] signaturePolicyDocumentData = this.signaturePolicyService.getSignaturePolicyDocument(); DigestAlgAndValueType sigPolicyHash = getDigestAlgAndValue(signaturePolicyDocumentData, this.xadesObjectFactory, this.xmldsigObjectFactory, this.digestAlgorithm); signaturePolicyId.setSigPolicyHash(sigPolicyHash); String signaturePolicyDownloadUrl = this.signaturePolicyService.getSignaturePolicyDownloadUrl(); if (null != signaturePolicyDownloadUrl) { SigPolicyQualifiersListType sigPolicyQualifiers = this.xadesObjectFactory .createSigPolicyQualifiersListType(); signaturePolicyId.setSigPolicyQualifiers(sigPolicyQualifiers); AnyType sigPolicyQualifier = this.xadesObjectFactory.createAnyType(); sigPolicyQualifiers.getSigPolicyQualifier().add(sigPolicyQualifier); JAXBElement<String> spUriElement = this.xadesObjectFactory.createSPURI(signaturePolicyDownloadUrl); sigPolicyQualifier.getContent().add(spUriElement); } } else if (this.signaturePolicyImplied) { SignaturePolicyIdentifierType signaturePolicyIdentifier = this.xadesObjectFactory .createSignaturePolicyIdentifierType(); signedSignatureProperties.setSignaturePolicyIdentifier(signaturePolicyIdentifier); signaturePolicyIdentifier.setSignaturePolicyImplied(""); } // DataObjectFormat if (false == this.dataObjectFormatMimeTypes.isEmpty()) { SignedDataObjectPropertiesType signedDataObjectProperties = this.xadesObjectFactory .createSignedDataObjectPropertiesType(); signedProperties.setSignedDataObjectProperties(signedDataObjectProperties); List<DataObjectFormatType> dataObjectFormats = signedDataObjectProperties.getDataObjectFormat(); for (Map.Entry<String, String> dataObjectFormatMimeType : this.dataObjectFormatMimeTypes.entrySet()) { DataObjectFormatType dataObjectFormat = this.xadesObjectFactory.createDataObjectFormatType(); dataObjectFormat.setObjectReference("#" + dataObjectFormatMimeType.getKey()); dataObjectFormat.setMimeType(dataObjectFormatMimeType.getValue()); dataObjectFormats.add(dataObjectFormat); } } // marshall XAdES QualifyingProperties Node qualifyingPropertiesNode = marshallQualifyingProperties(document, this.xadesObjectFactory, qualifyingProperties); // add XAdES ds:Object List<XMLStructure> xadesObjectContent = new LinkedList<XMLStructure>(); xadesObjectContent.add(new DOMStructure(qualifyingPropertiesNode)); XMLObject xadesObject = signatureFactory.newXMLObject(xadesObjectContent, null, null, null); objects.add(xadesObject); // add XAdES ds:Reference DigestMethod digestMethod = signatureFactory.newDigestMethod(digestAlgorithm.getXmlAlgoId(), null); List<Transform> transforms = new LinkedList<Transform>(); Transform exclusiveTransform = signatureFactory.newTransform(CanonicalizationMethod.INCLUSIVE, (TransformParameterSpec) null); transforms.add(exclusiveTransform); Reference reference = signatureFactory.newReference("#" + signedPropertiesId, digestMethod, transforms, XADES_TYPE, null); references.add(reference); }
From source file:org.apache.cxf.ws.security.sts.provider.operation.IssueDelegate.java
private void signXML(Element target, String refId, KeyStoreInfo keyStoreInfo) { org.apache.xml.security.Init.init(); XMLSignatureFactory signFactory = XMLSignatureFactory.getInstance(SIGN_FACTORY_TYPE); try {/*from ww w . j a va 2s .co m*/ DigestMethod method = signFactory.newDigestMethod(DigestMethod.SHA1, null); Transform transform = signFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null); Reference ref = signFactory.newReference('#' + refId, method, Collections.singletonList(transform), null, null); CanonicalizationMethod canonMethod = signFactory .newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null); SignatureMethod signMethod = signFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null); SignedInfo si = signFactory.newSignedInfo(canonMethod, signMethod, Collections.singletonList(ref)); KeyStore.PrivateKeyEntry keyEntry = getKeyEntry(keyStoreInfo); if (keyEntry == null) { throw new IllegalStateException("Key is not found in keystore. Alias: " + keyStoreInfo.getAlias()); } KeyInfo ki = getKeyInfo(signFactory, keyEntry); DOMSignContext dsc = new DOMSignContext(keyEntry.getPrivateKey(), target); XMLSignature signature = signFactory.newXMLSignature(si, ki); signature.sign(dsc); } catch (Exception e) { throw new STSException("Cannot sign xml document: " + e.getMessage(), e); } }