List of usage examples for javax.xml.crypto.dsig XMLSignatureFactory getInstance
public static XMLSignatureFactory getInstance()
XMLSignatureFactory
that supports the default XML processing mechanism and representation type ("DOM"). From source file:be.fedict.eid.dss.document.ooxml.OOXMLDSSDocumentService.java
@Override public List<SignatureInfo> verifySignatures(byte[] document, byte[] originalDocument) throws Exception { if (null != originalDocument) { throw new IllegalArgumentException("cannot perform original document verifications"); }// w ww. jav a 2 s . c om OOXMLSignatureVerifier ooxmlSignatureVerifier = new OOXMLSignatureVerifier(); List<String> signatureResourceNames = ooxmlSignatureVerifier.getSignatureResourceNames(document); List<SignatureInfo> signatureInfos = new LinkedList<SignatureInfo>(); XAdESValidation xadesValidation = new XAdESValidation(this.documentContext); for (String signatureResourceName : signatureResourceNames) { LOG.debug("signatureResourceName: " + signatureResourceName); Document signatureDocument = ooxmlSignatureVerifier .getSignatureDocument(new ByteArrayInputStream(document), signatureResourceName); if (null == signatureDocument) { continue; } NodeList signatureNodeList = signatureDocument.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); if (0 == signatureNodeList.getLength()) { continue; } Element signatureElement = (Element) signatureNodeList.item(0); xadesValidation.prepareDocument(signatureElement); KeyInfoKeySelector keySelector = new KeyInfoKeySelector(); DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, signatureElement); domValidateContext.setProperty("org.jcp.xml.dsig.validateManifests", Boolean.TRUE); OOXMLURIDereferencer dereferencer = new OOXMLURIDereferencer(document); domValidateContext.setURIDereferencer(dereferencer); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance(); XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext); LOG.debug("validating signature: " + xmlSignature.getId()); boolean valid = xmlSignature.validate(domValidateContext); LOG.debug("signature valid: " + valid); if (!valid) { LOG.error("signature invalid"); continue; } // check OOXML's XML DSig/XAdES requirements if (!ooxmlSignatureVerifier.isValidOOXMLSignature(xmlSignature, document)) { LOG.error("Invalid OOXML Signature"); continue; } X509Certificate signingCertificate = keySelector.getCertificate(); SignatureInfo signatureInfo = xadesValidation.validate(signatureDocument, xmlSignature, signatureElement, signingCertificate); signatureInfos.add(signatureInfo); } return signatureInfos; }
From source file:be.fedict.eid.dss.document.odf.ODFDSSDocumentService.java
@Override public List<SignatureInfo> verifySignatures(byte[] document, byte[] originalDocument) throws Exception { List<SignatureInfo> signatureInfos = new LinkedList<SignatureInfo>(); ZipInputStream odfZipInputStream = new ZipInputStream(new ByteArrayInputStream(document)); ZipEntry zipEntry;/* w w w . jav a2s. c o m*/ while (null != (zipEntry = odfZipInputStream.getNextEntry())) { if (ODFUtil.isSignatureFile(zipEntry)) { Document documentSignatures = ODFUtil.loadDocument(odfZipInputStream); NodeList signatureNodeList = documentSignatures.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); XAdESValidation xadesValidation = new XAdESValidation(this.documentContext); for (int idx = 0; idx < signatureNodeList.getLength(); idx++) { Element signatureElement = (Element) signatureNodeList.item(idx); //LOG.debug("signatureValue: "+signatureElement.getTextContent()); xadesValidation.prepareDocument(signatureElement); KeyInfoKeySelector keySelector = new KeyInfoKeySelector(); DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, signatureElement); ODFURIDereferencer dereferencer = new ODFURIDereferencer(document); domValidateContext.setURIDereferencer(dereferencer); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance(); XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext); boolean valid = xmlSignature.validate(domValidateContext); if (!valid) { LOG.debug("invalid signature"); continue; } checkIntegrity(xmlSignature, document, originalDocument); X509Certificate signingCertificate = keySelector.getCertificate(); SignatureInfo signatureInfo = xadesValidation.validate(documentSignatures, xmlSignature, signatureElement, signingCertificate); signatureInfos.add(signatureInfo); } return signatureInfos; } } return signatureInfos; }
From source file:be.fedict.eid.dss.document.asic.ASiCDSSDocumentService.java
@Override public List<SignatureInfo> verifySignatures(byte[] document, byte[] originalDocument) throws Exception { if (null != originalDocument) { throw new IllegalArgumentException("cannot perform original document verifications"); }//from ww w. j a v a 2s . c o m ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(document)); ZipEntry zipEntry; while (null != (zipEntry = zipInputStream.getNextEntry())) { if (ASiCUtil.isSignatureZipEntry(zipEntry)) { break; } } List<SignatureInfo> signatureInfos = new LinkedList<SignatureInfo>(); if (null == zipEntry) { return signatureInfos; } XAdESValidation xadesValidation = new XAdESValidation(this.documentContext); Document documentSignaturesDocument = ODFUtil.loadDocument(zipInputStream); NodeList signatureNodeList = documentSignaturesDocument.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); for (int idx = 0; idx < signatureNodeList.getLength(); idx++) { Element signatureElement = (Element) signatureNodeList.item(idx); xadesValidation.prepareDocument(signatureElement); KeyInfoKeySelector keySelector = new KeyInfoKeySelector(); DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, signatureElement); ASiCURIDereferencer dereferencer = new ASiCURIDereferencer(document); domValidateContext.setURIDereferencer(dereferencer); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance(); XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext); boolean valid = xmlSignature.validate(domValidateContext); if (!valid) { continue; } // check whether all files have been signed properly SignedInfo signedInfo = xmlSignature.getSignedInfo(); @SuppressWarnings("unchecked") List<Reference> references = signedInfo.getReferences(); Set<String> referenceUris = new HashSet<String>(); for (Reference reference : references) { String referenceUri = reference.getURI(); referenceUris.add(URLDecoder.decode(referenceUri, "UTF-8")); } zipInputStream = new ZipInputStream(new ByteArrayInputStream(document)); while (null != (zipEntry = zipInputStream.getNextEntry())) { if (ASiCUtil.isSignatureZipEntry(zipEntry)) { continue; } if (false == referenceUris.contains(zipEntry.getName())) { LOG.warn("no ds:Reference for ASiC entry: " + zipEntry.getName()); return signatureInfos; } } X509Certificate signer = keySelector.getCertificate(); SignatureInfo signatureInfo = xadesValidation.validate(documentSignaturesDocument, xmlSignature, signatureElement, signer); signatureInfos.add(signatureInfo); } return signatureInfos; }
From source file:be.fedict.eid.applet.service.signer.ooxml.OOXMLSignatureVerifier.java
public List<X509Certificate> getSigners(URL url) throws IOException, ParserConfigurationException, SAXException, TransformerException, MarshalException, XMLSignatureException, JAXBException { List<X509Certificate> signers = new LinkedList<X509Certificate>(); List<String> signatureResourceNames = getSignatureResourceNames(url); if (signatureResourceNames.isEmpty()) { LOG.debug("no signature resources"); }/* w w w.j ava 2s .c o m*/ for (String signatureResourceName : signatureResourceNames) { Document signatureDocument = getSignatureDocument(url, signatureResourceName); if (null == signatureDocument) { continue; } NodeList signatureNodeList = signatureDocument.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); if (0 == signatureNodeList.getLength()) { return null; } Node signatureNode = signatureNodeList.item(0); KeyInfoKeySelector keySelector = new KeyInfoKeySelector(); DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, signatureNode); domValidateContext.setProperty("org.jcp.xml.dsig.validateManifests", Boolean.TRUE); OOXMLURIDereferencer dereferencer = new OOXMLURIDereferencer(url); domValidateContext.setURIDereferencer(dereferencer); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance(); XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext); boolean valid = xmlSignature.validate(domValidateContext); if (!valid) { LOG.debug("not a valid signature"); continue; } /* * Check the content of idPackageObject. */ List<XMLObject> objects = xmlSignature.getObjects(); XMLObject idPackageObject = null; for (XMLObject object : objects) { if ("idPackageObject".equals(object.getId())) { idPackageObject = object; break; } } if (null == idPackageObject) { LOG.debug("idPackageObject ds:Object not present"); continue; } List<XMLStructure> idPackageObjectContent = idPackageObject.getContent(); Manifest idPackageObjectManifest = null; for (XMLStructure content : idPackageObjectContent) { if (content instanceof Manifest) { idPackageObjectManifest = (Manifest) content; break; } } if (null == idPackageObjectManifest) { LOG.debug("no ds:Manifest present within idPackageObject ds:Object"); continue; } LOG.debug("ds:Manifest present within idPackageObject ds:Object"); List<Reference> idPackageObjectReferences = idPackageObjectManifest.getReferences(); Set<String> idPackageObjectReferenceUris = new HashSet<String>(); Set<String> remainingIdPackageObjectReferenceUris = new HashSet<String>(); for (Reference idPackageObjectReference : idPackageObjectReferences) { idPackageObjectReferenceUris.add(idPackageObjectReference.getURI()); remainingIdPackageObjectReferenceUris.add(idPackageObjectReference.getURI()); } LOG.debug("idPackageObject ds:Reference URIs: " + idPackageObjectReferenceUris); CTTypes contentTypes = getContentTypes(url); List<String> relsEntryNames = getRelsEntryNames(url); for (String relsEntryName : relsEntryNames) { LOG.debug("---- relationship entry name: " + relsEntryName); CTRelationships relationships = getRelationships(url, relsEntryName); List<CTRelationship> relationshipList = relationships.getRelationship(); boolean includeRelationshipInSignature = false; for (CTRelationship relationship : relationshipList) { String relationshipType = relationship.getType(); STTargetMode targetMode = relationship.getTargetMode(); if (null != targetMode) { LOG.debug("TargetMode: " + targetMode.name()); if (targetMode == STTargetMode.EXTERNAL) { /* * 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 relationshipTarget = relationship.getTarget(); String baseUri = "/" + relsEntryName.substring(0, relsEntryName.indexOf("_rels/")); String streamEntry = baseUri + relationshipTarget; LOG.debug("stream entry: " + streamEntry); streamEntry = FilenameUtils.separatorsToUnix(FilenameUtils.normalize(streamEntry)); LOG.debug("normalized stream entry: " + streamEntry); String contentType = getContentType(contentTypes, streamEntry); if (relationshipType.endsWith("customXml")) { if (false == contentType.equals("inkml+xml") && false == contentType.equals("text/xml")) { LOG.debug("skipping customXml with content type: " + contentType); continue; } } includeRelationshipInSignature = true; LOG.debug("content type: " + contentType); String referenceUri = streamEntry + "?ContentType=" + contentType; LOG.debug("reference URI: " + referenceUri); if (false == idPackageObjectReferenceUris.contains(referenceUri)) { throw new RuntimeException( "no reference in idPackageObject ds:Object for relationship target: " + streamEntry); } remainingIdPackageObjectReferenceUris.remove(referenceUri); } String relsReferenceUri = "/" + relsEntryName + "?ContentType=application/vnd.openxmlformats-package.relationships+xml"; if (includeRelationshipInSignature && false == idPackageObjectReferenceUris.contains(relsReferenceUri)) { LOG.debug("missing ds:Reference for: " + relsEntryName); throw new RuntimeException("missing ds:Reference for: " + relsEntryName); } remainingIdPackageObjectReferenceUris.remove(relsReferenceUri); } if (false == remainingIdPackageObjectReferenceUris.isEmpty()) { LOG.debug("remaining idPackageObject reference URIs" + idPackageObjectReferenceUris); throw new RuntimeException("idPackageObject manifest contains unknown ds:References: " + remainingIdPackageObjectReferenceUris); } X509Certificate signer = keySelector.getCertificate(); signers.add(signer); } return signers; }
From source file:be.fedict.eid.dss.document.zip.ZIPDSSDocumentService.java
@Override public List<SignatureInfo> verifySignatures(byte[] document, byte[] originalDocument) throws Exception { ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(document)); ZipEntry zipEntry;// w w w. j ava2 s . c o m while (null != (zipEntry = zipInputStream.getNextEntry())) { if (ODFUtil.isSignatureFile(zipEntry)) { break; } } List<SignatureInfo> signatureInfos = new LinkedList<SignatureInfo>(); if (null == zipEntry) { return signatureInfos; } XAdESValidation xadesValidation = new XAdESValidation(this.documentContext); Document documentSignaturesDocument = ODFUtil.loadDocument(zipInputStream); NodeList signatureNodeList = documentSignaturesDocument.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); for (int idx = 0; idx < signatureNodeList.getLength(); idx++) { Element signatureElement = (Element) signatureNodeList.item(idx); xadesValidation.prepareDocument(signatureElement); KeyInfoKeySelector keySelector = new KeyInfoKeySelector(); DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, signatureElement); ZIPURIDereferencer dereferencer = new ZIPURIDereferencer(document); domValidateContext.setURIDereferencer(dereferencer); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance(); XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext); boolean valid = xmlSignature.validate(domValidateContext); if (!valid) { continue; } // check whether all files have been signed properly SignedInfo signedInfo = xmlSignature.getSignedInfo(); @SuppressWarnings("unchecked") List<Reference> references = signedInfo.getReferences(); Set<String> referenceUris = new HashSet<String>(); for (Reference reference : references) { String referenceUri = reference.getURI(); referenceUris.add(URLDecoder.decode(referenceUri, "UTF-8")); } zipInputStream = new ZipInputStream(new ByteArrayInputStream(document)); while (null != (zipEntry = zipInputStream.getNextEntry())) { if (ODFUtil.isSignatureFile(zipEntry)) { continue; } if (!referenceUris.contains(zipEntry.getName())) { LOG.warn("no ds:Reference for ZIP entry: " + zipEntry.getName()); return signatureInfos; } } if (null != originalDocument) { for (Reference reference : references) { if (null != reference.getType()) { /* * We skip XAdES and eID identity ds:Reference. */ continue; } String digestAlgo = reference.getDigestMethod().getAlgorithm(); LOG.debug("ds:Reference digest algo: " + digestAlgo); String referenceUri = reference.getURI(); LOG.debug("ds:Reference URI: " + referenceUri); byte[] digestValue = reference.getDigestValue(); org.apache.xml.security.signature.XMLSignature xmldsig = new org.apache.xml.security.signature.XMLSignature( documentSignaturesDocument, "", org.apache.xml.security.signature.XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA512, Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS); xmldsig.addDocument(referenceUri, null, digestAlgo); ResourceResolverSpi zipResourceResolver = new ZIPResourceResolver(originalDocument); xmldsig.addResourceResolver(zipResourceResolver); org.apache.xml.security.signature.SignedInfo apacheSignedInfo = xmldsig.getSignedInfo(); org.apache.xml.security.signature.Reference apacheReference = apacheSignedInfo.item(0); apacheReference.generateDigestValue(); byte[] originalDigestValue = apacheReference.getDigestValue(); if (!Arrays.equals(originalDigestValue, digestValue)) { throw new RuntimeException("not original document"); } } /* * So we already checked whether no files were changed, and that * no files were added compared to the original document. Still * have to check whether no files were removed. */ ZipInputStream originalZipInputStream = new ZipInputStream( new ByteArrayInputStream(originalDocument)); ZipEntry originalZipEntry; Set<String> referencedEntryNames = new HashSet<String>(); for (Reference reference : references) { if (null != reference.getType()) { continue; } referencedEntryNames.add(reference.getURI()); } while (null != (originalZipEntry = originalZipInputStream.getNextEntry())) { if (ODFUtil.isSignatureFile(originalZipEntry)) { continue; } if (!referencedEntryNames.contains(originalZipEntry.getName())) { LOG.warn("missing ds:Reference for ZIP entry: " + originalZipEntry.getName()); throw new RuntimeException( "missing ds:Reference for ZIP entry: " + originalZipEntry.getName()); } } } X509Certificate signer = keySelector.getCertificate(); SignatureInfo signatureInfo = xadesValidation.validate(documentSignaturesDocument, xmlSignature, signatureElement, signer); signatureInfos.add(signatureInfo); } return signatureInfos; }
From source file:com.vmware.identity.saml.impl.TokenAuthorityImpl.java
/** * Creates signature part of assertion. Uses digest method algorithm * corresponding to the signature algorithm used. * * @param assertion// w w w . java 2 s. com * @param signatureAlgorithm * @return */ private Element createSignatureAndSignAssertion(Assertion assertion, SignatureAlgorithm signatureAlgorithm, SignInfo signInfo) { assert assertion != null; assert signatureAlgorithm != null; XMLSignatureFactory factory = XMLSignatureFactory.getInstance(); Element assertionElement = marshallAssertion(assertion); List<Transform> transforms = createTransforms(); Reference ref = createReference(transforms, assertionElement.getAttribute(Assertion.ID_ATTRIB_NAME), // here we use the digest method which is corresponding to the // signature algorithm used signatureAlgorithm.getDigestMethod().toString()); SignedInfo signedInfo = createSignedInfo(Collections.singletonList(ref), signatureAlgorithm); DOMSignContext signingContext = new DOMSignContext(signInfo.getPrivateKey(), assertionElement); signingContext.putNamespacePrefix(SignatureConstants.TRANSFORM_C14N_EXCL_OMIT_COMMENTS, "ec"); signingContext.putNamespacePrefix(XMLSignature.XMLNS, "ds"); // signature should be the second section in the assertion - after issuer // here we are sure that the structure of assertion is as follows: // 1) issuer 2) subject // we get subject node and enter signature before it and the result is: // 1) issuer 2) signature 3) subject Node subjectNode = assertionElement.getChildNodes().item(1); signingContext.setNextSibling(subjectNode); log.debug("Set SigningContext into assertion (after Issuer or as a first child in the assertion DOM)."); final KeyInfo keyInfo = createKeyInfo(signInfo); XMLSignature xmlSignature = factory.newXMLSignature(signedInfo, keyInfo); try { final long start = System.nanoTime(); xmlSignature.sign(signingContext); perfLog.trace("'signature.sign' took {} ms.", TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start)); } catch (MarshalException e) { throw new IllegalStateException(e); } catch (XMLSignatureException e) { throw new IllegalStateException(e); } log.debug("Created Signature and sign it."); return assertionElement; }
From source file:com.vmware.identity.saml.impl.TokenAuthorityImpl.java
/** * Create KeyInfo section representation. * * @return KeyInfo/*from w w w. j a va 2 s.co m*/ */ private KeyInfo createKeyInfo(SignInfo signInfo) { List<? extends Certificate> stsCertificates = signInfo.getCertificationPath().getCertificates(); XMLSignatureFactory factory = XMLSignatureFactory.getInstance(); KeyInfoFactory keyInfoFactory = factory.getKeyInfoFactory(); X509Data certificatesData = keyInfoFactory.newX509Data(stsCertificates); log.debug("Created KeyInfo section from certificates: {}", stsCertificates); return keyInfoFactory.newKeyInfo(Collections.singletonList(certificatesData)); }
From source file:com.vmware.identity.saml.impl.TokenAuthorityImpl.java
/** * Creates SignedInfo section part of Signature. * * @param references/*from www . j a v a2 s .c o m*/ * references to be included in SignedInfo. Cannot be null. * @param signatureAlgorithm * @return returns SignedInfo object representing SignedInfo section * @throws NoSuchAlgorithmException * @throws InvalidAlgorithmParameterException */ private SignedInfo createSignedInfo(List<Reference> references, SignatureAlgorithm signatureAlgorithm) { assert references != null; assert signatureAlgorithm != null; XMLSignatureFactory factory = XMLSignatureFactory.getInstance(); CanonicalizationMethod canonicalizationMethod; try { canonicalizationMethod = factory.newCanonicalizationMethod( SignatureConstants.TRANSFORM_C14N_EXCL_OMIT_COMMENTS, (C14NMethodParameterSpec) null); } catch (Exception e) { throw new IllegalStateException("Cannot create canonicalization object.", e); } SignatureMethod signatureMethod; try { signatureMethod = factory.newSignatureMethod(signatureAlgorithm.toString(), null); } catch (Exception e) { throw new IllegalStateException("Cannot create signature algorithm object.", e); } SignedInfo signedInfo = factory.newSignedInfo(canonicalizationMethod, signatureMethod, references); log.debug("Created SignedInfo section with signatureAlgorithm: {}", signatureAlgorithm); return signedInfo; }
From source file:com.vmware.identity.saml.impl.TokenAuthorityImpl.java
/** * Creates a Reference part of Signature section * * @param transforms/* www . j a v a2 s . co m*/ * @param id * @param digestMethod * @return * @throws NoSuchAlgorithmException * @throws InvalidAlgorithmParameterException */ private Reference createReference(List<Transform> transforms, String id, String digestMethod) { assert transforms != null; assert id != null; assert digestMethod != null; XMLSignatureFactory factory = XMLSignatureFactory.getInstance(); javax.xml.crypto.dsig.DigestMethod digestAlgorithm; try { digestAlgorithm = factory.newDigestMethod(digestMethod, null); } catch (Exception e) { throw new IllegalStateException("Cannot create digest method object.", e); } log.debug("Created reference with id: {} and digestMethod: {}", id, digestMethod); return factory.newReference("#" + id, digestAlgorithm, transforms, null, null); }
From source file:com.vmware.identity.saml.impl.TokenAuthorityImpl.java
/** * Creates a list of transform part of Reference section in Signature * * @return// w ww. ja v a 2 s .c o m * @throws NoSuchAlgorithmException * @throws InvalidAlgorithmParameterException */ private List<Transform> createTransforms() { XMLSignatureFactory factory = XMLSignatureFactory.getInstance(); List<Transform> transforms = new ArrayList<Transform>(2); List<String> prefixList = new ArrayList<String>(2); prefixList.add(XMLConstants.XSD_PREFIX); prefixList.add(XMLConstants.XSI_PREFIX); try { transforms.add(factory.newTransform(CanonicalizationMethod.ENVELOPED, (TransformParameterSpec) null)); transforms.add( factory.newTransform(CanonicalizationMethod.EXCLUSIVE, new ExcC14NParameterSpec(prefixList))); } catch (Exception e) { throw new IllegalStateException("Cannot create enveloped or exclusive transform objects.", e); } log.debug("Created transforms: {} and {}", CanonicalizationMethod.ENVELOPED, CanonicalizationMethod.EXCLUSIVE); return transforms; }