List of usage examples for javax.xml.crypto.dsig.dom DOMValidateContext DOMValidateContext
public DOMValidateContext(Key validatingKey, Node node)
DOMValidateContext
containing the specified key and node. From source file:Signing.java
public static void main(String[] args) throws Exception { SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); SOAPPart soapPart = soapMessage.getSOAPPart(); SOAPEnvelope soapEnvelope = soapPart.getEnvelope(); SOAPHeader soapHeader = soapEnvelope.getHeader(); SOAPHeaderElement headerElement = soapHeader.addHeaderElement(soapEnvelope.createName("Signature", "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12")); SOAPBody soapBody = soapEnvelope.getBody(); soapBody.addAttribute(/*from ww w . ja va 2 s .co m*/ soapEnvelope.createName("id", "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12"), "Body"); Name bodyName = soapEnvelope.createName("FooBar", "z", "http://example.com"); SOAPBodyElement gltp = soapBody.addBodyElement(bodyName); Source source = soapPart.getContent(); Node root = null; if (source instanceof DOMSource) { root = ((DOMSource) source).getNode(); } else if (source instanceof SAXSource) { InputSource inSource = ((SAXSource) source).getInputSource(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = null; db = dbf.newDocumentBuilder(); Document doc = db.parse(inSource); root = (Node) doc.getDocumentElement(); } dumpDocument(root); KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA"); kpg.initialize(1024, new SecureRandom()); KeyPair keypair = kpg.generateKeyPair(); XMLSignatureFactory sigFactory = XMLSignatureFactory.getInstance(); Reference ref = sigFactory.newReference("#Body", sigFactory.newDigestMethod(DigestMethod.SHA1, null)); SignedInfo signedInfo = sigFactory.newSignedInfo( sigFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null), sigFactory.newSignatureMethod(SignatureMethod.DSA_SHA1, null), Collections.singletonList(ref)); KeyInfoFactory kif = sigFactory.getKeyInfoFactory(); KeyValue kv = kif.newKeyValue(keypair.getPublic()); KeyInfo keyInfo = kif.newKeyInfo(Collections.singletonList(kv)); XMLSignature sig = sigFactory.newXMLSignature(signedInfo, keyInfo); System.out.println("Signing the message..."); PrivateKey privateKey = keypair.getPrivate(); Element envelope = getFirstChildElement(root); Element header = getFirstChildElement(envelope); DOMSignContext sigContext = new DOMSignContext(privateKey, header); sigContext.putNamespacePrefix(XMLSignature.XMLNS, "ds"); sigContext.setIdAttributeNS(getNextSiblingElement(header), "http://schemas.xmlsoap.org/soap/security/2000-12", "id"); sig.sign(sigContext); dumpDocument(root); System.out.println("Validate the signature..."); Element sigElement = getFirstChildElement(header); DOMValidateContext valContext = new DOMValidateContext(keypair.getPublic(), sigElement); valContext.setIdAttributeNS(getNextSiblingElement(header), "http://schemas.xmlsoap.org/soap/security/2000-12", "id"); boolean valid = sig.validate(valContext); System.out.println("Signature valid? " + valid); }
From source file:Main.java
public static boolean validateDocumentByKey(final Document document, Key validatingKey) throws SignatureException { final DOMValidateContext valContext = new DOMValidateContext(validatingKey, getSignatureNode(document.getDocumentElement())); try {// www . j av a2s. c o m final XMLSignature signature = getXMLSignatureFactory().unmarshalXMLSignature(valContext); return signature.validate(valContext); } catch (final Exception e) { throw new SignatureException("Signature verification error", e); } }
From source file:be.fedict.eid.applet.service.signer.odf.ODFSignatureVerifier.java
private static X509Certificate getVerifiedSignatureSigner(URL odfUrl, Node signatureNode) throws MarshalException, XMLSignatureException { if (null == odfUrl) { throw new IllegalArgumentException("odfUrl is null"); }// ww w . ja va 2s. c om KeyInfoKeySelector keySelector = new KeyInfoKeySelector(); DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, signatureNode); ODFURIDereferencer dereferencer = new ODFURIDereferencer(odfUrl); domValidateContext.setURIDereferencer(dereferencer); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance(); LOG.debug("java version: " + System.getProperty("java.version")); /* * Requires Java 6u10 because of a bug. See also: * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6696582 */ XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext); boolean validity = xmlSignature.validate(domValidateContext); if (false == validity) { LOG.debug("invalid signature"); return null; } // TODO: check what has been signed. X509Certificate signer = keySelector.getCertificate(); if (null == signer) { throw new IllegalStateException("signer X509 certificate is null"); } LOG.debug("signer: " + signer.getSubjectX500Principal()); return signer; }
From source file:be.fedict.eid.applet.service.signer.xps.XPSSignatureVerifier.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); for (String signatureResourceName : signatureResourceNames) { LOG.debug("signature resource name: " + signatureResourceName); Document signatureDocument = loadDocument(url, signatureResourceName); if (null == signatureDocument) { LOG.warn("signature resource not found: " + signatureResourceName); continue; }//from w w w. ja v a 2s . co m NodeList signatureNodeList = signatureDocument.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); if (0 == signatureNodeList.getLength()) { LOG.debug("no signature elements present"); continue; } Node signatureNode = signatureNodeList.item(0); OPCKeySelector keySelector = new OPCKeySelector(url, signatureResourceName); 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 validity = xmlSignature.validate(domValidateContext); if (false == validity) { LOG.debug("not a valid signature"); continue; } // TODO: check what has been signed. X509Certificate signer = keySelector.getCertificate(); signers.add(signer); } return signers; }
From source file:be.e_contract.dssp.client.SignResponseVerifier.java
/** * Checks the signature on the SignResponse browser POST message. * /* w w w.j ava2 s . c o m*/ * @param signResponseMessage * the SignResponse message. * @param session * the session object. * @return the verification result object. * @throws JAXBException * @throws ParserConfigurationException * @throws SAXException * @throws IOException * @throws MarshalException * @throws XMLSignatureException * @throws Base64DecodingException * @throws UserCancelException * @throws ClientRuntimeException * @throws SubjectNotAuthorizedException */ public static SignResponseVerificationResult checkSignResponse(String signResponseMessage, DigitalSignatureServiceSession session) throws JAXBException, ParserConfigurationException, SAXException, IOException, MarshalException, XMLSignatureException, Base64DecodingException, UserCancelException, ClientRuntimeException, SubjectNotAuthorizedException { if (null == session) { throw new IllegalArgumentException("missing session"); } byte[] decodedSignResponseMessage; try { decodedSignResponseMessage = Base64.decode(signResponseMessage); } catch (Base64DecodingException e) { throw new SecurityException("no Base64"); } // JAXB parsing JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class, be.e_contract.dssp.ws.jaxb.dss.async.ObjectFactory.class, be.e_contract.dssp.ws.jaxb.wsa.ObjectFactory.class, be.e_contract.dssp.ws.jaxb.wsu.ObjectFactory.class); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); SignResponse signResponse; try { signResponse = (SignResponse) unmarshaller .unmarshal(new ByteArrayInputStream(decodedSignResponseMessage)); } catch (UnmarshalException e) { throw new SecurityException("no valid SignResponse XML"); } // DOM parsing DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); InputStream signResponseInputStream = new ByteArrayInputStream(decodedSignResponseMessage); Document signResponseDocument = documentBuilder.parse(signResponseInputStream); // signature verification NodeList signatureNodeList = signResponseDocument .getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "Signature"); if (signatureNodeList.getLength() != 1) { throw new SecurityException("requires 1 ds:Signature element"); } Element signatureElement = (Element) signatureNodeList.item(0); SecurityTokenKeySelector keySelector = new SecurityTokenKeySelector(session.getKey()); DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, signatureElement); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM"); XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext); boolean validSignature = xmlSignature.validate(domValidateContext); if (false == validSignature) { throw new SecurityException("invalid ds:Signature"); } // verify content String responseId = null; RelatesToType relatesTo = null; AttributedURIType to = null; TimestampType timestamp = null; String signerIdentity = null; AnyType optionalOutputs = signResponse.getOptionalOutputs(); List<Object> optionalOutputsList = optionalOutputs.getAny(); for (Object optionalOutputObject : optionalOutputsList) { LOG.debug("optional output object type: " + optionalOutputObject.getClass().getName()); if (optionalOutputObject instanceof JAXBElement) { JAXBElement optionalOutputElement = (JAXBElement) optionalOutputObject; LOG.debug("optional output name: " + optionalOutputElement.getName()); LOG.debug("optional output value type: " + optionalOutputElement.getValue().getClass().getName()); if (RESPONSE_ID_QNAME.equals(optionalOutputElement.getName())) { responseId = (String) optionalOutputElement.getValue(); } else if (optionalOutputElement.getValue() instanceof RelatesToType) { relatesTo = (RelatesToType) optionalOutputElement.getValue(); } else if (TO_QNAME.equals(optionalOutputElement.getName())) { to = (AttributedURIType) optionalOutputElement.getValue(); } else if (optionalOutputElement.getValue() instanceof TimestampType) { timestamp = (TimestampType) optionalOutputElement.getValue(); } else if (optionalOutputElement.getValue() instanceof NameIdentifierType) { NameIdentifierType nameIdentifier = (NameIdentifierType) optionalOutputElement.getValue(); signerIdentity = nameIdentifier.getValue(); } } } Result result = signResponse.getResult(); LOG.debug("result major: " + result.getResultMajor()); LOG.debug("result minor: " + result.getResultMinor()); if (DigitalSignatureServiceConstants.REQUESTER_ERROR_RESULT_MAJOR.equals(result.getResultMajor())) { if (DigitalSignatureServiceConstants.USER_CANCEL_RESULT_MINOR.equals(result.getResultMinor())) { throw new UserCancelException(); } if (DigitalSignatureServiceConstants.CLIENT_RUNTIME_RESULT_MINOR.equals(result.getResultMinor())) { throw new ClientRuntimeException(); } if (DigitalSignatureServiceConstants.SUBJECT_NOT_AUTHORIZED_RESULT_MINOR .equals(result.getResultMinor())) { throw new SubjectNotAuthorizedException(signerIdentity); } } if (false == DigitalSignatureServiceConstants.PENDING_RESULT_MAJOR.equals(result.getResultMajor())) { throw new SecurityException("invalid dss:ResultMajor"); } if (null == responseId) { throw new SecurityException("missing async:ResponseID"); } if (false == responseId.equals(session.getResponseId())) { throw new SecurityException("invalid async:ResponseID"); } if (null == relatesTo) { throw new SecurityException("missing wsa:RelatesTo"); } if (false == session.getInResponseTo().equals(relatesTo.getValue())) { throw new SecurityException("invalid wsa:RelatesTo"); } if (null == to) { throw new SecurityException("missing wsa:To"); } if (false == session.getDestination().equals(to.getValue())) { throw new SecurityException("invalid wsa:To"); } if (null == timestamp) { throw new SecurityException("missing wsu:Timestamp"); } AttributedDateTime expires = timestamp.getExpires(); if (null == expires) { throw new SecurityException("missing wsu:Timestamp/wsu:Expires"); } DateTime expiresDateTime = new DateTime(expires.getValue()); DateTime now = new DateTime(); if (now.isAfter(expiresDateTime)) { throw new SecurityException("wsu:Timestamp expired"); } session.setSignResponseVerified(true); SignResponseVerificationResult signResponseVerificationResult = new SignResponseVerificationResult( signerIdentity); return signResponseVerificationResult; }
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 w w . j a v a 2s. c o m*/ 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;//from w w w. j av a 2 s .com 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:com.vmware.identity.sts.ws.SignatureValidator.java
/** * Validates the request signature. If the signature is not valid the * relevant {@link WSFaultException} is thrown * * @param signatureNode//from w w w .j ava 2 s . c om * not null * @param signature * not null */ private void validateSignature(Node signatureNode, Signature signature, Node timestampNode) { assert signatureNode != null; assert signature != null; assert timestampNode != null; XMLSignatureFactory fac = XMLSignatureFactory.getInstance(); DOMValidateContext valContext = new DOMValidateContext(signature.getCertificate().getPublicKey(), signatureNode); try { XMLSignature xmlSignature = fac.unmarshalXMLSignature(valContext); if (!xmlSignature.validate(valContext)) { throw new WSFaultException(FaultKey.WSSE_FAILED_CHECK, "Signature is invalid."); } validateCanonicalizationMethod(xmlSignature); validateSignatureReferences(xmlSignature, valContext, signatureNode.getOwnerDocument(), timestampNode); } catch (MarshalException e) { throw new WSFaultException(FaultKey.WSSE_FAILED_CHECK, e); } catch (XMLSignatureException e) { throw new WSFaultException(FaultKey.WSSE_FAILED_CHECK, e); } }
From source file:gov.nih.nci.cacis.nav.DefaultNotificationValidator.java
@Override public void validateDigitalSignature(Node sig, final XDSDocumentResolver resolver) throws NotificationValidationException { boolean valid = false; try {/* w ww . j a v a2 s . c om*/ final DOMValidateContext valContext = new DOMValidateContext(getKeySelector(), sig); final XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); final XMLSignature signature = fac.unmarshalXMLSignature(valContext); // We cannot validate the References to documents in the XDS without // first retrieving them. So, for now, we can't do "core" validation. // We can only validate the Signature itself. valid = signature.getSignatureValue().validate(valContext); // CHECKSTYLE:OFF } catch (Exception ex) { // CHECKSTYLE:ON throw new NotificationValidationException("Error validating digital signature: " + ex.getMessage(), ex); } if (!valid) { throw new NotificationValidationException(ERR_SIG_VALIDATION_FAILED_MSG); } validateDocReferences(sig, resolver); }
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 w w w . j a va2 s .co 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; }