List of usage examples for javax.xml.crypto.dsig XMLSignature getKeyInfo
KeyInfo getKeyInfo();
XMLSignature
. From source file:module.signature.util.XAdESValidator.java
private static void validateSigner(Document document, Set<User> usersPermitted, Set<User> usersExcluded, boolean allUsersPermittedShouldBeThere) throws SignatureDataException { if (!allUsersPermittedShouldBeThere || ((usersExcluded != null) && !usersExcluded.isEmpty())) { //TODO implement it when needed throw new DomainException("method.not.yet.implemented"); }//from w w w . ja v a 2 s . c o m final String ID_NR_PREFIX = "OID.2.5.4.5=BI"; ArrayList<String> usersPermittedIdNumbers = new ArrayList<String>(); for (User user : usersPermitted) { usersPermittedIdNumbers.add(user.getPerson().getRemotePerson().getDocumentIdNumber()); } //let's extract each signature // XMLDSIG NodeList nlSignature = document.getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "Signature"); //DEBUG System.out.println("Got " + nlSignature.getLength() + " signatures"); if (nlSignature.getLength() < 1) { throw new SignatureException("could.not.find.a.signature.in.incoming.data", true, null); } HashSet<String> usersFoundIdNumbers = new HashSet<String>(); for (int i = 0; i < nlSignature.getLength(); i++) { //for each signature, let's extract the ID number of who did it Element signature = (Element) nlSignature.item(i); try { XMLSignature xmlSig = new XMLSignature(signature, null); KeyInfo ki = xmlSig.getKeyInfo(); String certificateIDNr = ki.getX509Certificate().getSubjectX500Principal().getName("RFC1779"); certificateIDNr = certificateIDNr .substring(certificateIDNr.indexOf(ID_NR_PREFIX) + ID_NR_PREFIX.length()); //let's take out the virgul and the last character, which is a control one certificateIDNr = certificateIDNr.substring(0, certificateIDNr.indexOf(',') - 1); usersFoundIdNumbers.add(certificateIDNr); } catch (XMLSignatureException e) { e.printStackTrace(); throw new SignatureDataException("signature.error.XMLSignatureExceptionError", e); } catch (XMLSecurityException e) { throw new SignatureDataException("signature.error.XMLSecurityException", e); } } //now let's validate the extracted info if (allUsersPermittedShouldBeThere && usersFoundIdNumbers.containsAll(usersPermittedIdNumbers)) { return; //TODO TODO URGENT uncomment the next two lines (just made possible to be able to test it!!) } else { throw new SignatureDataException("wrong.document.signer"); } //TODO the rest of the use cases aren't implemented ATM }
From source file:cl.nic.dte.util.XMLUtil.java
/** * Obtiene el certificado digital contenido en un nodo XML Sinature (<a * href="http://www.w3.org/TR/xmldsig-core/">http://www.w3.org/TR/xmldsig-core/</a>) * //w w w . j a v a2 s .com * @param signature * el nodo con el tag <Signature>. * @return El certificado digital contenido en el <KeyInfo> o * <code>null</code> en caso que el <Signature> no contenga * tal información. */ @SuppressWarnings("unchecked") public static X509Certificate getCertificate(XMLSignature signature) { String alg = signature.getSignedInfo().getSignatureMethod().getAlgorithm(); KeyInfo kinf = signature.getKeyInfo(); // Check for keyinfo if (kinf == null) { return null; } PublicKey pKey = null; List<X509Certificate> x509 = new ArrayList<X509Certificate>(); // I look for the public key and the certificates for (XMLStructure xst : (List<XMLStructure>) kinf.getContent()) { if (xst instanceof KeyValue) { PublicKey pk; try { pk = ((KeyValue) xst).getPublicKey(); if (algEquals(alg, pk.getAlgorithm())) pKey = pk; } catch (KeyException e) { // nothing } } if (xst instanceof X509Data) { for (Object cont : ((X509Data) xst).getContent()) if (cont instanceof X509Certificate) x509.add((X509Certificate) cont); } } // return of the certificates that matchs the public key. for (X509Certificate cert : x509) { if (cert.getPublicKey().equals(pKey)) { return cert; } } return null; }
From source file:module.signature.util.XAdESValidator.java
/** * @author joao.antunes@tagus.ist.utl.pt adapted it from {@link #validateXMLSignature(String)} * @param streamWithSignature//from w w w.java 2s . co m * the {@link InputStream} that has the signature content * @return true if it's valid, false otherwise */ public boolean validateXMLSignature(InputStream streamWithSignature) { try { // get the xsd schema Validator validator = schemaXSD.newValidator(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder parser = dbf.newDocumentBuilder(); ErrorHandler eh = new ErrorHandler() { @Override public void warning(SAXParseException exception) throws SAXException { throw new UnsupportedOperationException("Not supported yet.", exception); } @Override public void error(SAXParseException exception) throws SAXException { throw new UnsupportedOperationException("Not supported yet.", exception); } @Override public void fatalError(SAXParseException exception) throws SAXException { throw new UnsupportedOperationException("Not supported yet.", exception); } }; // parse the document parser.setErrorHandler(eh); Document document = parser.parse(streamWithSignature); // XAdES extension NodeList nlObject = document.getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "Object"); // XMLDSIG NodeList nlSignature = document.getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "Signature"); if (checkSchema) { if (nlObject.getLength() < 1) { return false; } if (nlSignature.getLength() < 1) { return false; } // parse the XML DOM tree againts the XSD schema validator.validate(new DOMSource(nlSignature.item(0))); } if (checkSignature) { // Validate Every Signature Element (including CounterSignatures) for (int i = 0; i < nlSignature.getLength(); i++) { Element signature = (Element) nlSignature.item(i); // String baseURI = fileToValidate.toURL().toString(); XMLSignature xmlSig = new XMLSignature(signature, null); KeyInfo ki = xmlSig.getKeyInfo(); // If signature contains X509Data if (ki.containsX509Data()) { NodeList nlSigningTime = signature.getElementsByTagNameNS(xadesNS, "SigningTime"); Date signingDate = null; if (nlSigningTime.item(0) != null) { StringBuilder xmlDate = new StringBuilder(nlSigningTime.item(0).getTextContent()) .deleteCharAt(22); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); signingDate = simpleDateFormat.parse(xmlDate.toString()); } //verificao OCSP //TODO FENIX-189 joantune: na realidade acho que isto no verifica mesmo a revocao.. a no ser que a keystore indicada seja actualizada regularmente. if (checkRevocation) { //keystore certs cc, raiz estado Security.setProperty("ocsp.enable", "true"); //System.setProperty("com.sun.security.enableCRLDP", "true"); CertificateFactory cf = CertificateFactory.getInstance("X.509"); CertPath certPath = cf .generateCertPath(Collections.singletonList(ki.getX509Certificate())); // TrustAnchor trustA = new TrustAnchor(ki.getX509Certificate(), null); // Set trustAnchors = Collections.singleton(trustA); PKIXParameters params = new PKIXParameters(cartaoCidadaoKeyStore); params.setRevocationEnabled(true); // validar o estado na data da assinatura if (nlSigningTime.item(0) != null) { params.setDate(signingDate); } try { CertPathValidator cpValidator = CertPathValidator.getInstance("PKIX"); CertPathValidatorResult result = cpValidator.validate(certPath, params); //TODO FENIX-196 probably one would want to send a notification here } catch (CertPathValidatorException ex) { return false; } catch (InvalidAlgorithmParameterException ex) { return false; } } // verifica a validade do certificado no momento da assinatura if (checkValidity) { if (nlSigningTime.item(0) != null) { // continue if there is no SigningTime, if CounterSignature isn't XAdES try { ki.getX509Certificate().checkValidity(signingDate); } catch (CertificateExpiredException ex) { return false; } catch (CertificateNotYetValidException ex) { return false; } } } // validate against Certificate Public Key boolean validSignature = xmlSig.checkSignatureValue(ki.getX509Certificate().getPublicKey()); if (!validSignature) { return false; } } // if signature includes KeyInfo KeyValue, also check against it if (ki.containsKeyValue()) { boolean validSignature = xmlSig.checkSignatureValue(ki.getPublicKey()); if (!validSignature) { return false; } } //let's check the SignatureTimeStamp(s) joantune NodeList signatureTimeStamps = signature.getElementsByTagNameNS("*", "SignatureTimeStamp"); Element signatureValue = null; if (signatureTimeStamps.getLength() > 0) { signatureValue = (Element) signature.getElementsByTagNameNS("*", "SignatureValue").item(0); } for (int j = 0; j < signatureTimeStamps.getLength(); j++) { logger.debug("Found a SignatureTimeStamp"); Element signatureTimeStamp = (Element) signatureTimeStamps.item(j); //for now we are ignoring the XMLTimeStamp element, let's iterate through all of the EncapsulatedTimeStamp that we find NodeList encapsulatedTimeStamps = signatureTimeStamp.getElementsByTagNameNS("*", "EncapsulatedTimeStamp"); for (int k = 0; k < encapsulatedTimeStamps.getLength(); k++) { logger.debug("Found an EncapsulatedTimeStamp"); Element encapsulatedTimeStamp = (Element) encapsulatedTimeStamps.item(k); //let's check it // note, we have the timestamptoken, not the whole response, that is, we don't have the status field ASN1Sequence signedTimeStampToken = ASN1Sequence .getInstance(Base64.decode(encapsulatedTimeStamp.getTextContent())); CMSSignedData cmsSignedData = new CMSSignedData( Base64.decode(encapsulatedTimeStamp.getTextContent())); TimeStampToken timeStampToken = new TimeStampToken(cmsSignedData); //let's construct the Request to make sure this is a valid response //let's generate the digest MessageDigest sha1 = MessageDigest.getInstance("SHA-1"); byte[] digest = sha1.digest(signatureValue.getTextContent().getBytes("UTF-8")); //let's make sure the digests are the same if (!Arrays.equals(digest, timeStampToken.getTimeStampInfo().getMessageImprintDigest())) { //TODO probably want to send an e-mail if this happens, as it's clearly a sign of tampering //FENIX-196 logger.debug("Found a different digest in the timestamp!"); return false; } try { //TODO for now we won't use the provided certificates that came with the TST // X509Store certificateStore = (X509Store) timeStampToken.getCertificates(); // JcaDigestCalculatorProviderBuilder builder = new JcaDigestCalculatorProviderBuilder(); // timeStampToken.validate(tsaCert, "BC"); // timeStampToken.validate(new SignerInformationVerifier(new JcaContentVerifierProviderBuilder() // .build(tsaCert), builder.build())); timeStampToken.validate(new SignerInformationVerifier( new JcaContentVerifierProviderBuilder().build(tsaCert), new BcDigestCalculatorProvider())); //let's just verify that the timestamp was done in the past :) - let's give a tolerance of 5 mins :) Date currentDatePlus5Minutes = new Date(); //let's make it go 5 minutes ahead currentDatePlus5Minutes.setMinutes(currentDatePlus5Minutes.getMinutes() + 5); if (!timeStampToken.getTimeStampInfo().getGenTime() .before(currentDatePlus5Minutes)) { //FENIX-196 probably we want to log this! //what the heck, timestamp is done in the future!! (clocks might be out of sync) logger.warn("Found a timestamp in the future!"); return false; } logger.debug("Found a valid TimeStamp!"); //as we have no other timestamp elements in this signature, this means all is ok! :) //(point 5) of g.2.2.16.1.3 on the specs } catch (TSPException exception) { logger.debug("TimeStamp response did not validate", exception); return false; } } } } } } catch (IOException ex) { Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex); return false; } catch (ParserConfigurationException ex) { Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex); return false; } catch (SAXException ex) { Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex); return false; } catch (Exception ex) { Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex); return false; } return true; }
From source file:org.apache.jcp.xml.dsig.internal.dom.DOMXMLSignature.java
@Override public boolean equals(Object o) { if (this == o) { return true; }// w w w .j a v a2 s. co m if (!(o instanceof XMLSignature)) { return false; } XMLSignature osig = (XMLSignature) o; boolean idEqual = (id == null ? osig.getId() == null : id.equals(osig.getId())); boolean keyInfoEqual = (ki == null ? osig.getKeyInfo() == null : ki.equals(osig.getKeyInfo())); return (idEqual && keyInfoEqual && sv.equals(osig.getSignatureValue()) && si.equals(osig.getSignedInfo()) && objects.equals(osig.getObjects())); }
From source file:org.roda.common.certification.ODFSignatureUtils.java
private static void verifyCertificates(Path input, Node signatureNode) throws MarshalException, XMLSignatureException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException, KeyStoreException { XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM"); DOMValidateContext domValidateContext = new DOMValidateContext(new KeyInfoKeySelector(), signatureNode); XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext); xmlSignature.getSignatureValue().validate(domValidateContext); // xmlSignature.validate(domValidateContext); KeyInfo keyInfo = xmlSignature.getKeyInfo(); Iterator<?> it = keyInfo.getContent().iterator(); List<X509Certificate> certs = new ArrayList<X509Certificate>(); List<CRL> crls = new ArrayList<CRL>(); while (it.hasNext()) { XMLStructure content = (XMLStructure) it.next(); if (content instanceof X509Data) { X509Data certdata = (X509Data) content; Object[] entries = certdata.getContent().toArray(); for (int i = 0; i < entries.length; i++) { if (entries[i] instanceof X509CRL) { X509CRL crl = (X509CRL) entries[i]; crls.add(crl);/*from ww w . j a v a2 s .co m*/ } if (entries[i] instanceof X509Certificate) { X509Certificate cert = (X509Certificate) entries[i]; cert.checkValidity(); certs.add(cert); } } } } for (CRL c : crls) { for (X509Certificate cert : certs) { if (c.isRevoked(cert)) throw new CertificateRevokedException(null, null, null, null); } } }
From source file:org.roda.core.plugins.plugins.characterization.ODFSignatureUtils.java
private static void verifyCertificates(Node signatureNode) throws MarshalException, XMLSignatureException, NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException { XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM"); DOMValidateContext domValidateContext = new DOMValidateContext(new KeyInfoKeySelector(), signatureNode); XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext); xmlSignature.getSignatureValue().validate(domValidateContext); // xmlSignature.validate(domValidateContext); KeyInfo keyInfo = xmlSignature.getKeyInfo(); Iterator<?> it = keyInfo.getContent().iterator(); List<X509Certificate> certs = new ArrayList<>(); List<CRL> crls = new ArrayList<>(); while (it.hasNext()) { XMLStructure content = (XMLStructure) it.next(); if (content instanceof X509Data) { X509Data certdata = (X509Data) content; Object[] entries = certdata.getContent().toArray(); for (int i = 0; i < entries.length; i++) { if (entries[i] instanceof X509CRL) { X509CRL crl = (X509CRL) entries[i]; crls.add(crl);/* w w w .jav a2 s .c o m*/ } if (entries[i] instanceof X509Certificate) { X509Certificate cert = (X509Certificate) entries[i]; cert.checkValidity(); certs.add(cert); } } } } for (CRL c : crls) { for (X509Certificate cert : certs) { if (c.isRevoked(cert)) throw new CertificateRevokedException(null, null, null, null); } } }