List of usage examples for javax.xml.crypto.dsig XMLSignature XMLNS
String XMLNS
To view the source code for javax.xml.crypto.dsig XMLSignature XMLNS.
Click Source Link
From source file:org.roda.core.plugins.plugins.characterization.ODFSignatureUtils.java
public static String runDigitalSignatureVerify(Path input) throws IOException { String result = "Passed"; try (ZipFile zipFile = new ZipFile(input.toString())) { ZipEntry documentSignatureEntry = null; Enumeration<?> enumeration; for (enumeration = zipFile.entries(); enumeration.hasMoreElements();) { ZipEntry entry = (ZipEntry) enumeration.nextElement(); if (META_INF_DOCUMENTSIGNATURES_XML.equalsIgnoreCase(entry.getName())) { documentSignatureEntry = entry; break; }/*from w w w . j av a2 s .c o m*/ } if (documentSignatureEntry != null) { try (InputStream zipStream = zipFile.getInputStream(documentSignatureEntry)) { InputSource inputSource = new InputSource(zipStream); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.parse(inputSource); NodeList signatureNodeList = document.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); for (int i = 0; i < signatureNodeList.getLength(); i++) { Node signatureNode = signatureNodeList.item(i); verifyCertificates(signatureNode); } } catch (ParserConfigurationException | SAXException e) { result = "Signatures document can not be parsed"; } catch (CertificateExpiredException e) { result = "Contains expired certificates"; } catch (CertificateRevokedException e) { result = "Contains revoked certificates"; } catch (CertificateNotYetValidException e) { result = "Contains certificates not yet valid"; } catch (MarshalException | XMLSignatureException e) { result = "Digital signatures are not valid"; } catch (KeyStoreException | CertificateException | NoSuchAlgorithmException e) { result = "Could not verify certificates"; } } else { result = "Could not find " + META_INF_DOCUMENTSIGNATURES_XML; } } return result; }
From source file:org.simbasecurity.core.saml.SAMLResponseHandlerImpl.java
@Override public boolean isValid(String... requestId) { try {//from w w w .j a va 2 s. com Calendar now = Calendar.getInstance(TimeZone.getTimeZone("UTC")); if (this.document == null) { throw new Exception("SAML Response is not loaded"); } if (this.currentUrl == null || this.currentUrl.isEmpty()) { throw new Exception("The URL of the current host was not established"); } // Check SAML version if (!rootElement.getAttribute("Version").equals("2.0")) { throw new Exception("Unsupported SAML Version."); } // Check ID in the response if (!rootElement.hasAttribute("ID")) { throw new Exception("Missing ID attribute on SAML Response."); } checkStatus(); if (!this.validateNumAssertions()) { throw new Exception("SAML Response must contain 1 Assertion."); } NodeList signNodes = document.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); ArrayList<String> signedElements = new ArrayList<>(); for (int i = 0; i < signNodes.getLength(); i++) { signedElements.add(signNodes.item(i).getParentNode().getLocalName()); } if (!signedElements.isEmpty()) { if (!this.validateSignedElements(signedElements)) { throw new Exception("Found an unexpected Signature Element. SAML Response rejected"); } } Document res = Utils.validateXML(this.document, "saml-schema-protocol-2.0.xsd"); if (res == null) { throw new Exception("Invalid SAML Response. Not match the saml-schema-protocol-2.0.xsd"); } if (rootElement.hasAttribute("InResponseTo")) { String responseInResponseTo = document.getDocumentElement().getAttribute("InResponseTo"); if (requestId.length > 0 && responseInResponseTo.compareTo(requestId[0]) != 0) { throw new Exception("The InResponseTo of the Response: " + responseInResponseTo + ", does not match the ID of the AuthNRequest sent by the SP: " + requestId[0]); } } // Validate Assertion timestamps if (!this.validateTimestamps()) { throw new Exception("Timing issues (please check your clock settings)"); } // EncryptedAttributes are not supported NodeList encryptedAttributeNodes = this .queryAssertion("/saml:AttributeStatement/saml:EncryptedAttribute"); if (encryptedAttributeNodes.getLength() > 0) { throw new Exception("There is an EncryptedAttribute in the Response and this SP not support them"); } // Check destination // TODO: lenneh: bktis: currentUrl is http:// and the destination is https:// // if (rootElement.hasAttribute("Destination")) { // String destinationUrl = rootElement.getAttribute("Destination"); // if (destinationUrl != null) { // if (!destinationUrl.equals(currentUrl)) { // throw new Exception("The response was received at " + currentUrl + " instead of " + destinationUrl); // } // } // } // Check Audience // TODO: lenneh: bktis: currentUrl is http:// and audienceUrl is https:// // Set<String> validAudiences = this.getAudiences(); // // if (validAudiences.isEmpty() || !this.audienceUrl.equals(currentUrl)) { // throw new Exception(this.audienceUrl + " is not a valid audience for this Response"); // } // Check the issuers Set<String> issuers = this.getIssuers(); for (String issuer : issuers) { if (issuer.isEmpty()) { throw new Exception("Invalid issuer in the Assertion/Response"); } } // Check the session Expiration Calendar sessionExpiration = this.getSessionNotOnOrAfter(); if (sessionExpiration != null) { if (now.equals(sessionExpiration) || now.after(sessionExpiration)) { throw new Exception( "The attributes have expired, based on the SessionNotOnOrAfter of the AttributeStatement of this Response"); } } // Check SubjectConfirmation, at least one SubjectConfirmation must be valid boolean validSubjectConfirmation = true; NodeList subjectConfirmationNodes = this.queryAssertion("/saml:Subject/saml:SubjectConfirmation"); for (int i = 0; i < subjectConfirmationNodes.getLength(); i++) { Node scn = subjectConfirmationNodes.item(i); Node method = scn.getAttributes().getNamedItem("Method"); if (method != null && !method.getNodeValue().equals(SAMLConstants.CM_BEARER)) { continue; } NodeList subjectConfirmationDataNodes = scn.getChildNodes(); for (int c = 0; c < subjectConfirmationDataNodes.getLength(); c++) { Node subjectConfirmationData = subjectConfirmationDataNodes.item(c); if (subjectConfirmationData.getNodeType() == Node.ELEMENT_NODE && subjectConfirmationData.getLocalName().equals("SubjectConfirmationData")) { // TODO: lenneh: bktis: currentUrl is http:// and the recipient is https:// // Node recipient = subjectConfirmationData.getAttributes().getNamedItem("Recipient"); // if (recipient != null && !recipient.getNodeValue().equals(currentUrl)) { // validSubjectConfirmation = false; // } Node notOnOrAfter = subjectConfirmationData.getAttributes().getNamedItem("NotOnOrAfter"); if (notOnOrAfter != null) { Calendar noa = javax.xml.bind.DatatypeConverter .parseDateTime(notOnOrAfter.getNodeValue()); if (now.equals(noa) || now.after(noa)) { validSubjectConfirmation = false; } } Node notBefore = subjectConfirmationData.getAttributes().getNamedItem("NotBefore"); if (notBefore != null) { Calendar nb = javax.xml.bind.DatatypeConverter.parseDateTime(notBefore.getNodeValue()); if (now.before(nb)) { validSubjectConfirmation = false; } } } } } if (!validSubjectConfirmation) { throw new Exception("A valid SubjectConfirmation was not found on this Response"); } if (signedElements.isEmpty()) { throw new Exception("No Signature found. SAML Response rejected"); } else { if (!Utils.validateSign(signNodes.item(0), certificate)) { throw new Exception("Signature validation failed. SAML Response rejected"); } } return true; } catch (Error e) { error.append(e.getMessage()); return false; } catch (Exception e) { e.printStackTrace(); error.append(e.getMessage()); return false; } }
From source file:org.wso2.carbon.identity.sts.mex.MexGetService.java
/** * This method adds EndPointReference element into Port element of the WSDL *//*from w w w.j a v a2 s. co m*/ private void addIIdentityAddressing(OMElement portElem, X509Certificate cert) throws AxisFault { if (log.isDebugEnabled()) { log.debug("addIIdentityAddressing - port Element found"); } try { Iterator ite = portElem.getChildElements(); String address = null; while (ite.hasNext()) { OMElement elem = (OMElement) ite.next(); if ("address".equals(elem.getLocalName())) { address = elem.getAttributeValue(new QName("", "location")); break; // only one address element } } if (address == null) { throw new AxisFault("Address inside Port Element is null"); } EndpointReference ref = new EndpointReference(address); OMFactory factory = portElem.getOMFactory(); // this is an OM bug // OMFactory factory = OMAbstractFactory.getOMFactory(); OMElement identityElem = factory .createOMElement(new QName(IdentityConstants.IDENTITY_ADDRESSING_NS, IDENTITY_LN)); OMNamespace ns = factory.createOMNamespace(XMLSignature.XMLNS, "dsig"); OMElement keyInfoElem = factory.createOMElement(KEY_INFO_LN, ns); OMElement X509DataElem = factory.createOMElement(X509DATA_LN, ns); OMElement X509CertElem = factory.createOMElement(X509CERT_LN, ns); byte[] byteArray = cert.getEncoded(); X509CertElem.setText(Base64.encode(byteArray)); X509DataElem.addChild(X509CertElem); keyInfoElem.addChild(X509DataElem); identityElem.addChild(keyInfoElem); ArrayList lst = new ArrayList(); lst.add(identityElem); ref.setExtensibleElements(lst); QName qname = new QName(AddressingConstants.Final.WSA_NAMESPACE, "EndpointReference", WSA_PREFIX); OMElement refElem = EndpointReferenceHelper.toOM(factory, ref, qname, AddressingConstants.Final.WSA_NAMESPACE); portElem.addChild(refElem); } catch (Exception e) { throw new AxisFault(e.getMessage(), e); } }
From source file:test.be.fedict.eid.dss.DigitalSignatureServiceTest.java
@Test public void testSignedDocument() throws Exception { // setup/*w w w. j a v a 2s. c o m*/ String documentStr = "<document><data id=\"id\">hello world</data></document>"; Document document = loadDocument(documentStr); signDocument(document); String signedDocument = toString(document); LOG.debug("signed document: " + signedDocument); NodeList signatureNodeList = document.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); assertEquals(1, signatureNodeList.getLength()); DigitalSignatureServiceClient client = new DigitalSignatureServiceClient(); // operate boolean result = client.verify(signedDocument.getBytes(), "text/xml"); // verify assertTrue(result); }
From source file:test.be.fedict.eid.dss.DigitalSignatureServiceTest.java
private void signDocument(Document document) throws IOException, PKCS11Exception, InterruptedException, NoSuchFieldException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, KeyStoreException, NoSuchAlgorithmException, CertificateException, UnrecoverableEntryException, InvalidAlgorithmParameterException, MarshalException, XMLSignatureException, CardException { Messages messages = new Messages(Locale.getDefault()); PcscEid pcscEid = new PcscEid(new TestView(), messages); if (false == pcscEid.isEidPresent()) { LOG.debug("insert eID..."); pcscEid.waitForEidPresent();//w w w . java2 s . co m } // PrivateKeyEntry privateKeyEntry = pcscEid.getPrivateKeyEntry(); PrivateKeyEntry privateKeyEntry = null; // TODO: refactor once Commons eID has been released. XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM"); XMLSignContext signContext = new DOMSignContext(privateKeyEntry.getPrivateKey(), document.getDocumentElement()); signContext.putNamespacePrefix(javax.xml.crypto.dsig.XMLSignature.XMLNS, "ds"); DigestMethod digestMethod = signatureFactory.newDigestMethod(DigestMethod.SHA1, null); Reference reference = signatureFactory.newReference("#id", digestMethod); SignatureMethod signatureMethod = signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null); CanonicalizationMethod canonicalizationMethod = signatureFactory.newCanonicalizationMethod( CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null); SignedInfo signedInfo = signatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod, Collections.singletonList(reference)); KeyInfoFactory keyInfoFactory = KeyInfoFactory.getInstance(); List<Object> x509DataObjects = new LinkedList<Object>(); X509Certificate signingCertificate = (X509Certificate) privateKeyEntry.getCertificate(); x509DataObjects.add(signingCertificate); X509Data x509Data = keyInfoFactory.newX509Data(x509DataObjects); List<Object> keyInfoContent = new LinkedList<Object>(); keyInfoContent.add(x509Data); KeyInfo keyInfo = keyInfoFactory.newKeyInfo(keyInfoContent); javax.xml.crypto.dsig.XMLSignature xmlSignature = signatureFactory.newXMLSignature(signedInfo, keyInfo); xmlSignature.sign(signContext); pcscEid.close(); }
From source file:test.unit.be.fedict.eid.applet.service.signer.AbstractODFSignatureServiceTest.java
private boolean hasOdfSignature(URL odfUrl, int signatureCount) throws IOException, ParserConfigurationException, SAXException, org.apache.xml.security.signature.XMLSignatureException, XMLSecurityException, MarshalException, XMLSignatureException { InputStream odfInputStream = odfUrl.openStream(); if (null == odfInputStream) { return false; }/*from www . ja va 2 s. c om*/ ZipInputStream odfZipInputStream = new ZipInputStream(odfInputStream); ZipEntry zipEntry; while (null != (zipEntry = odfZipInputStream.getNextEntry())) { LOG.debug(zipEntry.getName()); if (true == "META-INF/documentsignatures.xml".equals(zipEntry.getName())) { Document documentSignatures = loadDocument(odfZipInputStream); NodeList signatureNodeList = documentSignatures.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); assertEquals(signatureCount, signatureNodeList.getLength()); for (int idx = 0; idx < signatureNodeList.getLength(); idx++) { Node signatureNode = signatureNodeList.item(idx); if (false == verifySignature(odfUrl, signatureNode)) { LOG.debug("JSR105 says invalid signature"); return false; } } return true; } } LOG.debug("no documentsignatures.xml entry present"); return false; }
From source file:test.unit.be.fedict.eid.applet.service.signer.AbstractXmlSignatureServiceTest.java
@Test public void testSignEnvelopingDocument() throws Exception { // setup//from ww w . jav a 2 s . com 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 ww w .ja v a2 s .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//from w ww. ja va 2s .com 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/*from ww w. ja va 2 s. c om*/ 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); }