List of usage examples for javax.xml.crypto KeySelector singletonKeySelector
public static KeySelector singletonKeySelector(Key key)
KeySelector
that always selects the specified key, regardless of the KeyInfo
passed to it. From source file:eu.europa.ec.markt.dss.validation102853.tsl.TrustedListsCertificateSource.java
/** * Load a trusted list for the specified URL * * @param url/* w ww .j a v a2 s. c om*/ * @param signerCert * @return * @throws IOException */ private TrustStatusList getTrustStatusList(String url, X509Certificate signerCert) { InputStream input = null; try { input = dataLoader.get(url); if (input == null) { throw new DSSNullReturnedException("The loader returned a null InputStream for: " + url); } if (url.toLowerCase().endsWith(".zip")) { input = getZippedData(input); } Document doc = DSSXMLUtils.buildDOM(input); boolean coreValidity = true; if (checkSignature) { coreValidity = false; if (signerCert != null) { final NodeList signatureNodeList = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); if (signatureNodeList.getLength() == 0) { throw new DSSException("Not ETSI compliant signature. The Xml is not signed."); } if (signatureNodeList.getLength() > 1) { throw new DSSException("Not ETSI compliant signature. There is more than one signature."); } final Element signatureEl = (Element) signatureNodeList.item(0); final KeySelector keySelector = KeySelector.singletonKeySelector(signerCert.getPublicKey()); final DOMValidateContext valContext = new DOMValidateContext(keySelector, signatureEl); final TSLURIDereferencer tsluriDereferencer = new TSLURIDereferencer(signatureEl); valContext.setURIDereferencer(tsluriDereferencer); final XMLSignatureFactory factory = XMLSignatureFactory.getInstance("DOM"); final XMLSignature signature = factory.unmarshalXMLSignature(valContext); coreValidity = signature.validate(valContext); LOG.info("The TSL signature validity: " + coreValidity); } } final TrustStatusList tsl = TrustServiceListFactory.newInstance(doc); tsl.setWellSigned(coreValidity); return tsl; } catch (DSSException e) { throw e; } catch (Exception e) { throw new DSSException(e); } finally { DSSUtils.closeQuietly(input); } }
From source file:eu.europa.ec.markt.dss.validation.xades.XAdESSignature.java
@Override public boolean checkIntegrity(Document detachedDocument) { DOMValidateContext valContext = new DOMValidateContext( KeySelector.singletonKeySelector(getSigningCertificate().getPublicKey()), this.signatureElement); if (detachedDocument != null) { valContext.setURIDereferencer(new OneExternalFileURIDereferencer("detached-file", detachedDocument)); }// w w w .j a v a 2 s .com XMLSignatureFactory factory = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI()); try { XMLSignature signature = factory.unmarshalXMLSignature(valContext); recursiveIdBrowse(valContext, signatureElement); boolean r = signature.validate(valContext); return r; } catch (MarshalException e) { throw new RuntimeException(e); } catch (XMLSignatureException e) { throw new RuntimeException(e); } }
From source file:eu.europa.ec.markt.dss.validation102853.xades.XAdESSignature.java
@Override public SignatureCryptographicVerification checkIntegrity(DSSDocument detachedDocument) { final SignatureCryptographicVerification scv = new SignatureCryptographicVerification(); final CertificateToken certToken = getSigningCertificate().getCertToken(); if (certToken != null) { final PublicKey publicKey = certToken.getCertificate().getPublicKey(); final KeySelector keySelector = KeySelector.singletonKeySelector(publicKey); /**/*from w ww . ja v a 2 s . c o m*/ * Creating a Validation Context<br> * We create an XMLValidateContext instance containing input parameters for validating the signature. Since we * are using DOM, we instantiate a DOMValidateContext instance (a subclass of XMLValidateContext), and pass it * two parameters, a KeyValueKeySelector object and a reference to the Signature element to be validated (which * is the first entry of the NodeList we generated earlier): */ final DOMValidateContext valContext = new DOMValidateContext(keySelector, signatureElement); try { URIDereferencer dereferencer = new ExternalFileURIDereferencer(detachedDocument); valContext.setURIDereferencer(dereferencer); /** * This property controls whether or not the digested Reference objects will cache the dereferenced content * and pre-digested input for subsequent retrieval via the Reference.getDereferencedData and * Reference.getDigestInputStream methods. The default value if not specified is Boolean.FALSE. */ valContext.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE); /** * Unmarshalling the XML Signature<br> * We extract the contents of the Signature element into an XMLSignature object. This process is called * unmarshalling. The Signature element is unmarshalled using an XMLSignatureFactory object. An application * can obtain a DOM implementation of XMLSignatureFactory by calling the following line of code: */ // These providers do not support ECDSA algorithm // factory = XMLSignatureFactory.getInstance("DOM"); // factory = XMLSignatureFactory.getInstance("DOM", "XMLDSig"); // factory = XMLSignatureFactory.getInstance("DOM", new org.jcp.xml.dsig.internal.dom.XMLDSigRI()); // This provider support ECDSA signature /** * ApacheXMLDSig / Apache Santuario XMLDSig (DOM XMLSignatureFactory; DOM KeyInfoFactory; C14N 1.0, C14N * 1.1, Exclusive C14N, Base64, Enveloped, XPath, XPath2, XSLT TransformServices)<br> * If this library is used than the same library must be used for the URIDereferencer. */ final XMLSignatureFactory factory = XMLSignatureFactory.getInstance("DOM", xmlProvider); /** * We then invoke the unmarshalXMLSignature method of the factory to unmarshal an XMLSignature object, and * pass it the validation context we created earlier: */ final XMLSignature signature = factory.unmarshalXMLSignature(valContext); //System.out.println("XMLSignature class: " + signature.getClass()); // Austrian specific signature //org.apache.xml.security.signature.XMLSignature signature_ = null; // try { // signature_ = new org.apache.xml.security.signature.XMLSignature(signatureElement, ""); // } catch (Exception e) { // // throw new DSSException(e); // } // signature.addResourceResolver(new XPointerResourceResolver(signatureElement)); //signature_.getSignedInfo().verifyReferences();//getVerificationResult(1); /** * In case of org.apache.jcp.xml.dsig.internal.dom.XMLDSigRI() provider, the ID attributes need to be set * manually.<br> * The DSSXMLUtils.recursiveIdBrowse(...) method do not take into account the XML outside of the Signature * tag. It prevents some signatures to be validated.<br> * * Solution: the following lines where added: */ final Document document = signatureElement.getOwnerDocument(); final Element rootElement = document.getDocumentElement(); if (rootElement.hasAttribute(DSSXMLUtils.ID_ATTRIBUTE_NAME)) { valContext.setIdAttributeNS(rootElement, null, DSSXMLUtils.ID_ATTRIBUTE_NAME); } DSSXMLUtils.recursiveIdBrowse(valContext, rootElement); /** * Validating the XML Signature<br> * Now we are ready to validate the signature. We do this by invoking the validate method on the * XMLSignature object, and pass it the validation context as follows: */ boolean coreValidity = false; try { coreValidity = signature.validate(valContext); } catch (XMLSignatureException e) { scv.setErrorMessage("Signature validation: " + e.getMessage()); } boolean signatureValidity = coreValidity; boolean dataFound = true; boolean dataHashValid = true; /** * If the XMLSignature.validate method returns false, we can try to narrow down the cause of the failure. * There are two phases in core XML Signature validation: <br> * - Signature validation (the cryptographic verification of the signature)<br> * - Reference validation (the verification of the digest of each reference in the signature)<br> * Each phase must be successful for the signature to be valid. To check if the signature failed to * cryptographically validate, we can check the status, as follows: */ try { signatureValidity = signature.getSignatureValue().validate(valContext); } catch (XMLSignatureException e) { scv.setErrorMessage(e.getMessage()); } @SuppressWarnings("unchecked") final List<Reference> references = signature.getSignedInfo().getReferences(); for (Reference reference : references) { boolean refHashValidity = false; try { refHashValidity = reference.validate(valContext); } catch (XMLSignatureException e) { scv.setErrorMessage(reference.getURI() + ": " + e.getMessage()); } dataHashValid = dataHashValid && refHashValidity; if (LOG.isLoggable(Level.INFO)) { LOG.info("Reference hash validity checked: " + reference.getURI() + "=" + refHashValidity); } final Data data = reference.getDereferencedData(); dataFound = dataFound && (data != null); final InputStream digestInputStream = reference.getDigestInputStream(); if (data != null && digestInputStream != null) { // The references are saved for later treatment in -A level. try { IOUtils.copy(digestInputStream, referencesDigestOutputStream); } catch (IOException e) { } } } scv.setReferenceDataFound(dataFound); scv.setReferenceDataIntact(dataHashValid); scv.setSignatureIntegrity(signatureValidity); } catch (MarshalException e) { scv.setErrorMessage(e.getMessage()); } } else { scv.setErrorMessage( "Unable to proceed with the signature cryptographic verification. There is no signing certificate!"); } return scv; }
From source file:test.unit.be.fedict.eid.applet.service.signer.AbstractXmlSignatureServiceTest.java
@Test public void testSignEnvelopingDocument() throws Exception { // setup//w w w. j av a2 s . c o m DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.newDocument(); Element rootElement = document.createElementNS("urn:test", "tns:root"); rootElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:tns", "urn:test"); document.appendChild(rootElement); Element dataElement = document.createElementNS("urn:test", "tns:data"); dataElement.setAttributeNS(null, "Id", "id-1234"); dataElement.setIdAttribute("Id", true); dataElement.setTextContent("data to be signed"); rootElement.appendChild(dataElement); SignatureTestFacet signatureFacet = new SignatureTestFacet(); signatureFacet.addReferenceUri("#id-1234"); XmlSignatureTestService testedInstance = new XmlSignatureTestService(signatureFacet); testedInstance.setEnvelopingDocument(document); testedInstance.setSignatureDescription("test-signature-description"); // operate DigestInfo digestInfo = testedInstance.preSign(null, null); // verify assertNotNull(digestInfo); LOG.debug("digest info description: " + digestInfo.description); assertEquals("test-signature-description", digestInfo.description); assertNotNull(digestInfo.digestValue); LOG.debug("digest algo: " + digestInfo.digestAlgo); assertEquals("SHA-1", digestInfo.digestAlgo); TemporaryTestDataStorage temporaryDataStorage = (TemporaryTestDataStorage) testedInstance .getTemporaryDataStorage(); assertNotNull(temporaryDataStorage); InputStream tempInputStream = temporaryDataStorage.getTempInputStream(); assertNotNull(tempInputStream); Document tmpDocument = PkiTestUtils.loadDocument(tempInputStream); LOG.debug("tmp document: " + PkiTestUtils.toString(tmpDocument)); Element nsElement = tmpDocument.createElement("ns"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:ds", Constants.SignatureSpecNS); Node digestValueNode = XPathAPI.selectSingleNode(tmpDocument, "//ds:DigestValue", nsElement); assertNotNull(digestValueNode); String digestValueTextContent = digestValueNode.getTextContent(); LOG.debug("digest value text content: " + digestValueTextContent); assertFalse(digestValueTextContent.isEmpty()); /* * Sign the received XML signature digest value. */ KeyPair keyPair = PkiTestUtils.generateKeyPair(); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPrivate()); byte[] digestInfoValue = ArrayUtils.addAll(PkiTestUtils.SHA1_DIGEST_INFO_PREFIX, digestInfo.digestValue); byte[] signatureValue = cipher.doFinal(digestInfoValue); DateTime notBefore = new DateTime(); DateTime notAfter = notBefore.plusYears(1); X509Certificate certificate = PkiTestUtils.generateCertificate(keyPair.getPublic(), "CN=Test", notBefore, notAfter, null, keyPair.getPrivate(), true, 0, null, null, new KeyUsage(KeyUsage.nonRepudiation)); /* * Operate: postSign */ testedInstance.postSign(signatureValue, Collections.singletonList(certificate)); byte[] signedDocumentData = testedInstance.getSignedDocumentData(); assertNotNull(signedDocumentData); Document signedDocument = PkiTestUtils.loadDocument(new ByteArrayInputStream(signedDocumentData)); LOG.debug("signed document: " + PkiTestUtils.toString(signedDocument)); NodeList signatureNodeList = signedDocument.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); assertEquals(1, signatureNodeList.getLength()); Node signatureNode = signatureNodeList.item(0); DOMValidateContext domValidateContext = new DOMValidateContext( KeySelector.singletonKeySelector(keyPair.getPublic()), signatureNode); domValidateContext.setIdAttributeNS((Element) signedDocument.getDocumentElement().getFirstChild(), null, "Id"); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance(); XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext); boolean validity = xmlSignature.validate(domValidateContext); assertTrue(validity); }
From source file:test.unit.be.fedict.eid.applet.service.signer.AbstractXmlSignatureServiceTest.java
@Test public void testSignExternalUri() throws Exception { // setup//from w w w . j a v a2s . c o m DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.newDocument(); SignatureTestFacet signatureFacet = new SignatureTestFacet(); signatureFacet.addReferenceUri("external-uri"); XmlSignatureTestService testedInstance = new XmlSignatureTestService(signatureFacet); testedInstance.setEnvelopingDocument(document); testedInstance.setSignatureDescription("test-signature-description"); UriTestDereferencer uriDereferencer = new UriTestDereferencer(); uriDereferencer.addResource("external-uri", "hello world".getBytes()); testedInstance.setUriDereferencer(uriDereferencer); // operate DigestInfo digestInfo = testedInstance.preSign(null, null); // verify assertNotNull(digestInfo); LOG.debug("digest info description: " + digestInfo.description); assertEquals("test-signature-description", digestInfo.description); assertNotNull(digestInfo.digestValue); LOG.debug("digest algo: " + digestInfo.digestAlgo); assertEquals("SHA-1", digestInfo.digestAlgo); TemporaryTestDataStorage temporaryDataStorage = (TemporaryTestDataStorage) testedInstance .getTemporaryDataStorage(); assertNotNull(temporaryDataStorage); InputStream tempInputStream = temporaryDataStorage.getTempInputStream(); assertNotNull(tempInputStream); Document tmpDocument = PkiTestUtils.loadDocument(tempInputStream); LOG.debug("tmp document: " + PkiTestUtils.toString(tmpDocument)); Element nsElement = tmpDocument.createElement("ns"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:ds", Constants.SignatureSpecNS); Node digestValueNode = XPathAPI.selectSingleNode(tmpDocument, "//ds:DigestValue", nsElement); assertNotNull(digestValueNode); String digestValueTextContent = digestValueNode.getTextContent(); LOG.debug("digest value text content: " + digestValueTextContent); assertFalse(digestValueTextContent.isEmpty()); /* * Sign the received XML signature digest value. */ KeyPair keyPair = PkiTestUtils.generateKeyPair(); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPrivate()); byte[] digestInfoValue = ArrayUtils.addAll(PkiTestUtils.SHA1_DIGEST_INFO_PREFIX, digestInfo.digestValue); byte[] signatureValue = cipher.doFinal(digestInfoValue); DateTime notBefore = new DateTime(); DateTime notAfter = notBefore.plusYears(1); X509Certificate certificate = PkiTestUtils.generateCertificate(keyPair.getPublic(), "CN=Test", notBefore, notAfter, null, keyPair.getPrivate(), true, 0, null, null, new KeyUsage(KeyUsage.nonRepudiation)); /* * Operate: postSign */ testedInstance.postSign(signatureValue, Collections.singletonList(certificate)); byte[] signedDocumentData = testedInstance.getSignedDocumentData(); assertNotNull(signedDocumentData); Document signedDocument = PkiTestUtils.loadDocument(new ByteArrayInputStream(signedDocumentData)); LOG.debug("signed document: " + PkiTestUtils.toString(signedDocument)); NodeList signatureNodeList = signedDocument.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); assertEquals(1, signatureNodeList.getLength()); Node signatureNode = signatureNodeList.item(0); DOMValidateContext domValidateContext = new DOMValidateContext( KeySelector.singletonKeySelector(keyPair.getPublic()), signatureNode); domValidateContext.setURIDereferencer(uriDereferencer); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance(); XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext); boolean validity = xmlSignature.validate(domValidateContext); assertTrue(validity); }
From source file:test.unit.be.fedict.eid.applet.service.signer.AbstractXmlSignatureServiceTest.java
@Test public void testSignEnvelopingDocumentWithExternalDigestInfo() throws Exception { // setup//w w w . ja v a2 s. c om DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.newDocument(); Element rootElement = document.createElementNS("urn:test", "tns:root"); rootElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:tns", "urn:test"); document.appendChild(rootElement); XmlSignatureTestService testedInstance = new XmlSignatureTestService(); testedInstance.setEnvelopingDocument(document); testedInstance.setSignatureDescription("test-signature-description"); byte[] refData = "hello world".getBytes(); MessageDigest messageDigest = MessageDigest.getInstance("SHA-1"); messageDigest.update(refData); byte[] digestValue = messageDigest.digest(); DigestInfo refDigestInfo = new DigestInfo(digestValue, "SHA-1", "urn:test:ref"); // operate DigestInfo digestInfo = testedInstance.preSign(Collections.singletonList(refDigestInfo), null); // verify assertNotNull(digestInfo); LOG.debug("digest info description: " + digestInfo.description); assertEquals("test-signature-description", digestInfo.description); assertNotNull(digestInfo.digestValue); LOG.debug("digest algo: " + digestInfo.digestAlgo); assertEquals("SHA-1", digestInfo.digestAlgo); TemporaryTestDataStorage temporaryDataStorage = (TemporaryTestDataStorage) testedInstance .getTemporaryDataStorage(); assertNotNull(temporaryDataStorage); InputStream tempInputStream = temporaryDataStorage.getTempInputStream(); assertNotNull(tempInputStream); Document tmpDocument = PkiTestUtils.loadDocument(tempInputStream); LOG.debug("tmp document: " + PkiTestUtils.toString(tmpDocument)); Element nsElement = tmpDocument.createElement("ns"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:ds", Constants.SignatureSpecNS); Node digestValueNode = XPathAPI.selectSingleNode(tmpDocument, "//ds:DigestValue", nsElement); assertNotNull(digestValueNode); String digestValueTextContent = digestValueNode.getTextContent(); LOG.debug("digest value text content: " + digestValueTextContent); assertFalse(digestValueTextContent.isEmpty()); /* * Sign the received XML signature digest value. */ KeyPair keyPair = PkiTestUtils.generateKeyPair(); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPrivate()); byte[] digestInfoValue = ArrayUtils.addAll(PkiTestUtils.SHA1_DIGEST_INFO_PREFIX, digestInfo.digestValue); byte[] signatureValue = cipher.doFinal(digestInfoValue); DateTime notBefore = new DateTime(); DateTime notAfter = notBefore.plusYears(1); X509Certificate certificate = PkiTestUtils.generateCertificate(keyPair.getPublic(), "CN=Test", notBefore, notAfter, null, keyPair.getPrivate(), true, 0, null, null, new KeyUsage(KeyUsage.nonRepudiation)); /* * Operate: postSign */ testedInstance.postSign(signatureValue, Collections.singletonList(certificate)); byte[] signedDocumentData = testedInstance.getSignedDocumentData(); assertNotNull(signedDocumentData); Document signedDocument = PkiTestUtils.loadDocument(new ByteArrayInputStream(signedDocumentData)); LOG.debug("signed document: " + PkiTestUtils.toString(signedDocument)); NodeList signatureNodeList = signedDocument.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); assertEquals(1, signatureNodeList.getLength()); Node signatureNode = signatureNodeList.item(0); DOMValidateContext domValidateContext = new DOMValidateContext( KeySelector.singletonKeySelector(keyPair.getPublic()), signatureNode); URIDereferencer dereferencer = new URITest2Dereferencer(); domValidateContext.setURIDereferencer(dereferencer); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance(); XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext); boolean validity = xmlSignature.validate(domValidateContext); assertTrue(validity); }
From source file:test.unit.be.fedict.eid.applet.service.signer.AbstractXmlSignatureServiceTest.java
@Test public void testSignExternalDigestInfo() throws Exception { // setup/* w w w . ja v a2s . co m*/ DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.newDocument(); XmlSignatureTestService testedInstance = new XmlSignatureTestService(); testedInstance.setEnvelopingDocument(document); testedInstance.setSignatureDescription("test-signature-description"); byte[] refData = "hello world".getBytes(); MessageDigest messageDigest = MessageDigest.getInstance("SHA-1"); messageDigest.update(refData); byte[] digestValue = messageDigest.digest(); DigestInfo refDigestInfo = new DigestInfo(digestValue, "SHA-1", "urn:test:ref"); // operate DigestInfo digestInfo = testedInstance.preSign(Collections.singletonList(refDigestInfo), null); // verify assertNotNull(digestInfo); LOG.debug("digest info description: " + digestInfo.description); assertEquals("test-signature-description", digestInfo.description); assertNotNull(digestInfo.digestValue); LOG.debug("digest algo: " + digestInfo.digestAlgo); assertEquals("SHA-1", digestInfo.digestAlgo); TemporaryTestDataStorage temporaryDataStorage = (TemporaryTestDataStorage) testedInstance .getTemporaryDataStorage(); assertNotNull(temporaryDataStorage); InputStream tempInputStream = temporaryDataStorage.getTempInputStream(); assertNotNull(tempInputStream); Document tmpDocument = PkiTestUtils.loadDocument(tempInputStream); LOG.debug("tmp document: " + PkiTestUtils.toString(tmpDocument)); Element nsElement = tmpDocument.createElement("ns"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:ds", Constants.SignatureSpecNS); Node digestValueNode = XPathAPI.selectSingleNode(tmpDocument, "//ds:DigestValue", nsElement); assertNotNull(digestValueNode); String digestValueTextContent = digestValueNode.getTextContent(); LOG.debug("digest value text content: " + digestValueTextContent); assertFalse(digestValueTextContent.isEmpty()); /* * Sign the received XML signature digest value. */ KeyPair keyPair = PkiTestUtils.generateKeyPair(); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPrivate()); byte[] digestInfoValue = ArrayUtils.addAll(PkiTestUtils.SHA1_DIGEST_INFO_PREFIX, digestInfo.digestValue); byte[] signatureValue = cipher.doFinal(digestInfoValue); DateTime notBefore = new DateTime(); DateTime notAfter = notBefore.plusYears(1); X509Certificate certificate = PkiTestUtils.generateCertificate(keyPair.getPublic(), "CN=Test", notBefore, notAfter, null, keyPair.getPrivate(), true, 0, null, null, new KeyUsage(KeyUsage.nonRepudiation)); /* * Operate: postSign */ testedInstance.postSign(signatureValue, Collections.singletonList(certificate)); byte[] signedDocumentData = testedInstance.getSignedDocumentData(); assertNotNull(signedDocumentData); Document signedDocument = PkiTestUtils.loadDocument(new ByteArrayInputStream(signedDocumentData)); LOG.debug("signed document: " + PkiTestUtils.toString(signedDocument)); NodeList signatureNodeList = signedDocument.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); assertEquals(1, signatureNodeList.getLength()); Node signatureNode = signatureNodeList.item(0); DOMValidateContext domValidateContext = new DOMValidateContext( KeySelector.singletonKeySelector(keyPair.getPublic()), signatureNode); URIDereferencer dereferencer = new URITest2Dereferencer(); domValidateContext.setURIDereferencer(dereferencer); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance(); XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext); boolean validity = xmlSignature.validate(domValidateContext); assertTrue(validity); }
From source file:test.unit.be.fedict.eid.applet.service.signer.AbstractXmlSignatureServiceTest.java
@Test public void testSignEnvelopingDocumentWithDTD() throws Exception { // setup//from w ww . ja v a 2 s .c o m InputStream documentInputStream = AbstractXmlSignatureServiceTest.class .getResourceAsStream("/bookstore.xml"); InputSource inputSource = new InputSource(documentInputStream); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); EntityResolver entityResolver = new MyEntityResolver(); documentBuilder.setEntityResolver(entityResolver); Document document = documentBuilder.parse(inputSource); SignatureFacet signatureFacet = new EnvelopedSignatureFacet(); XmlSignatureTestService testedInstance = new XmlSignatureTestService(signatureFacet); testedInstance.setEnvelopingDocument(document); testedInstance.setSignatureDescription("test-signature-description"); // operate DigestInfo digestInfo = testedInstance.preSign(null, null); // verify assertNotNull(digestInfo); LOG.debug("digest info description: " + digestInfo.description); assertEquals("test-signature-description", digestInfo.description); assertNotNull(digestInfo.digestValue); LOG.debug("digest algo: " + digestInfo.digestAlgo); assertEquals("SHA-1", digestInfo.digestAlgo); TemporaryTestDataStorage temporaryDataStorage = (TemporaryTestDataStorage) testedInstance .getTemporaryDataStorage(); assertNotNull(temporaryDataStorage); InputStream tempInputStream = temporaryDataStorage.getTempInputStream(); assertNotNull(tempInputStream); Document tmpDocument = PkiTestUtils.loadDocument(tempInputStream); LOG.debug("tmp document: " + PkiTestUtils.toString(tmpDocument)); Element nsElement = tmpDocument.createElement("ns"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:ds", Constants.SignatureSpecNS); Node digestValueNode = XPathAPI.selectSingleNode(tmpDocument, "//ds:DigestValue", nsElement); assertNotNull(digestValueNode); String digestValueTextContent = digestValueNode.getTextContent(); LOG.debug("digest value text content: " + digestValueTextContent); assertFalse(digestValueTextContent.isEmpty()); /* * Sign the received XML signature digest value. */ KeyPair keyPair = PkiTestUtils.generateKeyPair(); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPrivate()); byte[] digestInfoValue = ArrayUtils.addAll(PkiTestUtils.SHA1_DIGEST_INFO_PREFIX, digestInfo.digestValue); byte[] signatureValue = cipher.doFinal(digestInfoValue); DateTime notBefore = new DateTime(); DateTime notAfter = notBefore.plusYears(1); X509Certificate certificate = PkiTestUtils.generateCertificate(keyPair.getPublic(), "CN=Test", notBefore, notAfter, null, keyPair.getPrivate(), true, 0, null, null, new KeyUsage(KeyUsage.nonRepudiation)); /* * Operate: postSign */ testedInstance.postSign(signatureValue, Collections.singletonList(certificate)); byte[] signedDocumentData = testedInstance.getSignedDocumentData(); assertNotNull(signedDocumentData); Document signedDocument = PkiTestUtils.loadDocument(new ByteArrayInputStream(signedDocumentData)); LOG.debug("signed document: " + PkiTestUtils.toString(signedDocument)); NodeList signatureNodeList = signedDocument.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); assertEquals(1, signatureNodeList.getLength()); Node signatureNode = signatureNodeList.item(0); DOMValidateContext domValidateContext = new DOMValidateContext( KeySelector.singletonKeySelector(keyPair.getPublic()), signatureNode); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance(); XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext); boolean validity = xmlSignature.validate(domValidateContext); assertTrue(validity); }
From source file:test.unit.be.fedict.eid.applet.service.signer.AbstractXmlSignatureServiceTest.java
@Test public void testSignExternalXMLDocument() throws Exception { // setup/*from w w w. j a v a 2s . co m*/ DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.newDocument(); Element rootElement = document.createElementNS("urn:test", "tns:root"); rootElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:tns", "urn:test"); document.appendChild(rootElement); SignatureTestFacet signatureFacet = new SignatureTestFacet(); signatureFacet.addReferenceUri("/bookstore.xml"); XmlSignatureTestService testedInstance = new XmlSignatureTestService(signatureFacet); testedInstance.setUriDereferencer(new MyURIDereferencer()); testedInstance.setEnvelopingDocument(document); testedInstance.setSignatureDescription("test-signature-description"); // operate DigestInfo digestInfo = testedInstance.preSign(null, null); // verify assertNotNull(digestInfo); LOG.debug("digest info description: " + digestInfo.description); assertEquals("test-signature-description", digestInfo.description); assertNotNull(digestInfo.digestValue); LOG.debug("digest algo: " + digestInfo.digestAlgo); assertEquals("SHA-1", digestInfo.digestAlgo); TemporaryTestDataStorage temporaryDataStorage = (TemporaryTestDataStorage) testedInstance .getTemporaryDataStorage(); assertNotNull(temporaryDataStorage); InputStream tempInputStream = temporaryDataStorage.getTempInputStream(); assertNotNull(tempInputStream); Document tmpDocument = PkiTestUtils.loadDocument(tempInputStream); LOG.debug("tmp document: " + PkiTestUtils.toString(tmpDocument)); Element nsElement = tmpDocument.createElement("ns"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:ds", Constants.SignatureSpecNS); Node digestValueNode = XPathAPI.selectSingleNode(tmpDocument, "//ds:DigestValue", nsElement); assertNotNull(digestValueNode); String digestValueTextContent = digestValueNode.getTextContent(); LOG.debug("digest value text content: " + digestValueTextContent); assertFalse(digestValueTextContent.isEmpty()); /* * Sign the received XML signature digest value. */ KeyPair keyPair = PkiTestUtils.generateKeyPair(); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPrivate()); byte[] digestInfoValue = ArrayUtils.addAll(PkiTestUtils.SHA1_DIGEST_INFO_PREFIX, digestInfo.digestValue); byte[] signatureValue = cipher.doFinal(digestInfoValue); DateTime notBefore = new DateTime(); DateTime notAfter = notBefore.plusYears(1); X509Certificate certificate = PkiTestUtils.generateCertificate(keyPair.getPublic(), "CN=Test", notBefore, notAfter, null, keyPair.getPrivate(), true, 0, null, null, new KeyUsage(KeyUsage.nonRepudiation)); /* * Operate: postSign */ testedInstance.postSign(signatureValue, Collections.singletonList(certificate)); byte[] signedDocumentData = testedInstance.getSignedDocumentData(); assertNotNull(signedDocumentData); Document signedDocument = PkiTestUtils.loadDocument(new ByteArrayInputStream(signedDocumentData)); LOG.debug("signed document: " + PkiTestUtils.toString(signedDocument)); NodeList signatureNodeList = signedDocument.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); assertEquals(1, signatureNodeList.getLength()); Node signatureNode = signatureNodeList.item(0); DOMValidateContext domValidateContext = new DOMValidateContext( KeySelector.singletonKeySelector(keyPair.getPublic()), signatureNode); /* * Required to resolve the external XML document. */ domValidateContext.setURIDereferencer(new MyURIDereferencer()); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance(); XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext); boolean validity = xmlSignature.validate(domValidateContext); assertTrue(validity); }
From source file:test.unit.be.fedict.eid.applet.service.signer.XAdESSignatureFacetTest.java
@Test public void testSignEnvelopingDocument() throws Exception { // setup//from www . j a v a2s . c o m EnvelopedSignatureFacet envelopedSignatureFacet = new EnvelopedSignatureFacet(); KeyInfoSignatureFacet keyInfoSignatureFacet = new KeyInfoSignatureFacet(true, false, false); SignaturePolicyService signaturePolicyService = null; //SignaturePolicyService signaturePolicyService = new ExplicitSignaturePolicyService( // "urn:test", "hello world".getBytes(), "description", // "http://here.com"); XAdESSignatureFacet xadesSignatureFacet = new XAdESSignatureFacet(signaturePolicyService); TimeStampService mockTimeStampService = EasyMock.createMock(TimeStampService.class); RevocationDataService mockRevocationDataService = EasyMock.createMock(RevocationDataService.class); XAdESXLSignatureFacet xadesXLSignatureFacet = new XAdESXLSignatureFacet(mockTimeStampService, mockRevocationDataService); XmlSignatureTestService testedInstance = new XmlSignatureTestService(envelopedSignatureFacet, keyInfoSignatureFacet, xadesSignatureFacet, xadesXLSignatureFacet); KeyPair keyPair = PkiTestUtils.generateKeyPair(); DateTime notBefore = new DateTime(); DateTime notAfter = notBefore.plusYears(1); X509Certificate certificate = PkiTestUtils.generateCertificate(keyPair.getPublic(), "CN=Test", notBefore, notAfter, null, keyPair.getPrivate(), true, 0, null, null, new KeyUsage(KeyUsage.nonRepudiation)); List<X509Certificate> certificateChain = new LinkedList<X509Certificate>(); /* * We need at least 2 certificates for the XAdES-C complete certificate * refs construction. */ certificateChain.add(certificate); certificateChain.add(certificate); RevocationData revocationData = new RevocationData(); final X509CRL crl = PkiTestUtils.generateCrl(certificate, keyPair.getPrivate()); revocationData.addCRL(crl); OCSPResp ocspResp = PkiTestUtils.createOcspResp(certificate, false, certificate, certificate, keyPair.getPrivate(), "SHA1withRSA"); revocationData.addOCSP(ocspResp.getEncoded()); // expectations EasyMock.expect(mockTimeStampService.timeStamp(EasyMock.anyObject(byte[].class), EasyMock.anyObject(RevocationData.class))).andStubAnswer(new IAnswer<byte[]>() { public byte[] answer() throws Throwable { Object[] arguments = EasyMock.getCurrentArguments(); RevocationData revocationData = (RevocationData) arguments[1]; revocationData.addCRL(crl); return "time-stamp-token".getBytes(); } }); EasyMock.expect(mockRevocationDataService.getRevocationData(EasyMock.eq(certificateChain))) .andStubReturn(revocationData); // prepare EasyMock.replay(mockTimeStampService, mockRevocationDataService); // operate DigestInfo digestInfo = testedInstance.preSign(null, certificateChain); // verify assertNotNull(digestInfo); assertEquals("SHA-1", digestInfo.digestAlgo); assertNotNull(digestInfo.digestValue); TemporaryTestDataStorage temporaryDataStorage = (TemporaryTestDataStorage) testedInstance .getTemporaryDataStorage(); assertNotNull(temporaryDataStorage); InputStream tempInputStream = temporaryDataStorage.getTempInputStream(); assertNotNull(tempInputStream); Document tmpDocument = PkiTestUtils.loadDocument(tempInputStream); LOG.debug("tmp document: " + PkiTestUtils.toString(tmpDocument)); Element nsElement = tmpDocument.createElement("ns"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:ds", Constants.SignatureSpecNS); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:xades", "http://uri.etsi.org/01903/v1.3.2#"); Node digestValueNode = XPathAPI.selectSingleNode(tmpDocument, "//ds:DigestValue", nsElement); assertNotNull(digestValueNode); String digestValueTextContent = digestValueNode.getTextContent(); LOG.debug("digest value text content: " + digestValueTextContent); assertFalse(digestValueTextContent.isEmpty()); /* * Sign the received XML signature digest value. */ Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPrivate()); byte[] digestInfoValue = ArrayUtils.addAll(PkiTestUtils.SHA1_DIGEST_INFO_PREFIX, digestInfo.digestValue); byte[] signatureValue = cipher.doFinal(digestInfoValue); /* * Operate: postSign */ testedInstance.postSign(signatureValue, certificateChain); // verify EasyMock.verify(mockTimeStampService, mockRevocationDataService); byte[] signedDocumentData = testedInstance.getSignedDocumentData(); assertNotNull(signedDocumentData); Document signedDocument = PkiTestUtils.loadDocument(new ByteArrayInputStream(signedDocumentData)); LOG.debug("signed document: " + PkiTestUtils.toString(signedDocument)); NodeList signatureNodeList = signedDocument.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); assertEquals(1, signatureNodeList.getLength()); Node signatureNode = signatureNodeList.item(0); DOMValidateContext domValidateContext = new DOMValidateContext( KeySelector.singletonKeySelector(keyPair.getPublic()), signatureNode); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance(); XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext); boolean validity = xmlSignature.validate(domValidateContext); assertTrue(validity); File tmpFile = File.createTempFile("xades-x-l-", ".xml"); FileUtils.writeStringToFile(tmpFile, PkiTestUtils.toString(signedDocument)); LOG.debug("tmp file: " + tmpFile.getAbsolutePath()); Node resultNode = XPathAPI.selectSingleNode(signedDocument, "ds:Signature/ds:Object/xades:QualifyingProperties/xades:SignedProperties/xades:SignedSignatureProperties/xades:SigningCertificate/xades:Cert/xades:CertDigest/ds:DigestValue", nsElement); assertNotNull(resultNode); // also test whether the XAdES extension is in line with the XAdES XML // Schema. // stax-api 1.0.1 prevents us from using // "XMLConstants.W3C_XML_SCHEMA_NS_URI" Node qualifyingPropertiesNode = XPathAPI.selectSingleNode(signedDocument, "ds:Signature/ds:Object/xades:QualifyingProperties", nsElement); SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); LSResourceResolver xadesResourceResolver = new XAdESLSResourceResolver(); factory.setResourceResolver(xadesResourceResolver); InputStream schemaInputStream = XAdESSignatureFacetTest.class.getResourceAsStream("/XAdESv141.xsd"); Source schemaSource = new StreamSource(schemaInputStream); Schema schema = factory.newSchema(schemaSource); Validator validator = schema.newValidator(); // DOMResult gives some DOMException... validator.validate(new DOMSource(qualifyingPropertiesNode)); StreamSource streamSource = new StreamSource(tmpFile.toURI().toString()); ByteArrayOutputStream resultOutputStream = new ByteArrayOutputStream(); StreamResult streamResult = new StreamResult(resultOutputStream); // validator.validate(streamSource, streamResult); LOG.debug("result: " + resultOutputStream); }