public int compare(Object o1, Object o2) { X509Certificate c1 = (X509Certificate) o1; X509Certificate c2 = (X509Certificate) o2; if (c1 == c2) // this deals with case where both are null { return 0; } if (c1 == null) // non-null is always bigger than null { return -1; } if (c2 == null) { return 1; } if (c1.equals(c2)) { return 0; } Date d1 = c1.getNotAfter(); Date d2 = c2.getNotAfter(); int c = d1.compareTo(d2); if (c == 0) { String s1 = JavaImpl.getSubjectX500(c1); String s2 = JavaImpl.getSubjectX500(c2); c = s1.compareTo(s2); if (c == 0) { s1 = JavaImpl.getIssuerX500(c1); s2 = JavaImpl.getIssuerX500(c2); c = s1.compareTo(s2); if (c == 0) { BigInteger big1 = c1.getSerialNumber(); BigInteger big2 = c2.getSerialNumber(); c = big1.compareTo(big2); if (c == 0) { try { byte[] b1 = c1.getEncoded(); byte[] b2 = c2.getEncoded(); int len1 = b1.length; int len2 = b2.length; int i = 0; for (; i < len1 && i < len2; i++) { c = ((int) b1[i]) - ((int) b2[i]); if (c != 0) { break; } } if (c == 0) { c = b1.length - b2.length; } } catch (CertificateEncodingException cee) { // I give up. They can be equal if they // really want to be this badly. c = 0; } } } } } return c; }
@Override protected HttpURLConnection openConnection(String path, String query) throws IOException { query = addDelegationTokenParam(query); final URL url = new URL("https", nnAddr.getHostName(), nnAddr.getPort(), path + '?' + query); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); // bypass hostname verification try { conn.setHostnameVerifier(new DummyHostnameVerifier()); conn.setRequestMethod("GET"); conn.connect(); } catch (IOException ioe) { throwIOExceptionFromConnection(conn, ioe); } // check cert expiration date final int warnDays = ExpWarnDays; if (warnDays > 0) { // make sure only check once ExpWarnDays = 0; long expTimeThreshold = warnDays * MM_SECONDS_PER_DAY + System.currentTimeMillis(); X509Certificate[] clientCerts = (X509Certificate[]) conn.getLocalCertificates(); if (clientCerts != null) { for (X509Certificate cert : clientCerts) { long expTime = cert.getNotAfter().getTime(); if (expTime < expTimeThreshold) { StringBuilder sb = new StringBuilder(); sb.append("\n Client certificate " + cert.getSubjectX500Principal().getName()); int dayOffSet = (int) ((expTime - System.currentTimeMillis()) / MM_SECONDS_PER_DAY); sb.append(" have " + dayOffSet + " days to expire"); LOG.warn(sb.toString()); } } } } return (HttpURLConnection) conn; }
/** Add a new user and an expire service. Test that the service expires the users password */ @Test public void testExpireCertificateWithCertificateProfiles() throws Exception { final String certificateprofilename = "testExpireCertificateWithCertificateProfiles"; int certificateProfileId = certificateProfileSession.addCertificateProfile( admin, certificateprofilename, new CertificateProfile()); try { createCertificate(certificateProfileId); long seconds = (cert.getNotAfter().getTime() - new Date().getTime()) / 1000l; // Create a new UserPasswordExpireService ServiceConfiguration config = new ServiceConfiguration(); config.setActive(true); config.setDescription("This is a description"); // No mailsending for this Junit test service config.setActionClassPath(NoAction.class.getName()); config.setActionProperties(null); config.setIntervalClassPath(PeriodicalInterval.class.getName()); Properties intervalprop = new Properties(); // Run the service every 3:rd second intervalprop.setProperty(PeriodicalInterval.PROP_VALUE, "3"); intervalprop.setProperty(PeriodicalInterval.PROP_UNIT, PeriodicalInterval.UNIT_SECONDS); config.setIntervalProperties(intervalprop); config.setWorkerClassPath(CertificateExpirationNotifierWorker.class.getName()); Properties workerprop = new Properties(); workerprop.setProperty(EmailSendingWorkerConstants.PROP_SENDTOADMINS, "FALSE"); workerprop.setProperty(EmailSendingWorkerConstants.PROP_SENDTOENDUSERS, "FALSE"); workerprop.setProperty(BaseWorker.PROP_CAIDSTOCHECK, String.valueOf(caid)); workerprop.setProperty( BaseWorker.PROP_CERTIFICATE_PROFILE_IDS_TO_CHECK, Integer.toString(certificateProfileId)); workerprop.setProperty(BaseWorker.PROP_TIMEBEFOREEXPIRING, String.valueOf(seconds - 5)); workerprop.setProperty(BaseWorker.PROP_TIMEUNIT, BaseWorker.UNIT_SECONDS); config.setWorkerProperties(workerprop); if (serviceSession.getService(CERTIFICATE_EXPIRATION_SERVICE) == null) { serviceSession.addService(admin, 4711, CERTIFICATE_EXPIRATION_SERVICE, config); } serviceSession.activateServiceTimer(admin, CERTIFICATE_EXPIRATION_SERVICE); // The service will run... the cert should still be active after 2 // seconds.. Thread.sleep(2000); info = certificateStoreSession.getCertificateInfo(fingerprint); assertEquals("status does not match.", CertificateConstants.CERT_ACTIVE, info.getStatus()); // The service will run...We need some tolerance since timers cannot // be guaranteed to executed at the exact interval. Thread.sleep(10000); int tries = 0; while (info.getStatus() != CertificateConstants.CERT_NOTIFIEDABOUTEXPIRATION && tries < 5) { Thread.sleep(1000); info = certificateStoreSession.getCertificateInfo(fingerprint); tries++; } info = certificateStoreSession.getCertificateInfo(fingerprint); assertEquals( "Status does not match.", CertificateConstants.CERT_NOTIFIEDABOUTEXPIRATION, info.getStatus()); } finally { // Clean the certificate profile certificateProfileSession.removeCertificateProfile(admin, certificateprofilename); } }
/** @see de.willuhn.datasource.GenericObject#getAttribute(java.lang.String) */ public Object getAttribute(String arg0) throws RemoteException { if ("name".equals(arg0)) { String s = myCert.getSubject().getAttribute(Principal.COMMON_NAME); if (s == null || s.length() == 0) { s = this.cert.getSubjectDN().getName(); if (s != null && s.length() > 40) s = s.substring(0, 39) + "..."; return s; } return s; } if ("issuer".equals(arg0)) { String s = myCert.getIssuer().getAttribute(Principal.COMMON_NAME); if (s == null || s.length() == 0) s = myCert.getIssuer().getAttribute(Principal.ORGANIZATION); if (s == null || s.length() == 0) { s = this.cert.getIssuerDN().getName(); if (s != null && s.length() > 40) s = s.substring(0, 39) + "..."; } return s; } if ("serial".equals(arg0)) return cert.getSerialNumber().toString(); if ("organization".equals(arg0)) return myCert.getSubject().getAttribute(Principal.ORGANIZATION); if ("ou".equals(arg0)) return myCert.getSubject().getAttribute(Principal.ORGANIZATIONAL_UNIT); if ("datefrom".equals(arg0)) return cert.getNotBefore(); if ("dateto".equals(arg0)) return cert.getNotAfter(); return null; }
private SignatureData getFromXmlDigSigSignature( SignatureVerificationRequest signatureVerificationRequest, SignatureVerificationResponse response) throws ParserConfigurationException, SAXException, IOException, MarshalException, SignatureException { String signature = new String(Base64.decode(signatureVerificationRequest.getSignature())); InputStream is = new ByteArrayInputStream(signature.getBytes()); Document document = createDocument(is, true); XMLSignature xmlSignature = XMLSignatureFactory.getInstance().unmarshalXMLSignature(new DOMStructure(document)); List contentList = xmlSignature.getKeyInfo().getContent(); for (Object content : contentList) { if (content instanceof X509Data) { List certificateList = ((X509Data) content).getContent(); for (Object certificateObject : certificateList) { if (certificateObject instanceof X509Certificate) { X509Certificate cert = (X509Certificate) certificateObject; CertificateInfo ci = new CertificateInfo(); ci.setSubjectDn(cert.getSubjectDN().getName()); ci.setValidTo(simpleDateFormat.format(cert.getNotAfter())); response.getCertificateInfos().getCertificateInfo().add(ci); } } } } return createSignatureDataFromXmlDigSig(signature); }
private void parseCert() { try { FileInputStream fis = new FileInputStream("e:\\rongyifu.der"); CertificateFactory cf = CertificateFactory.getInstance("X509"); X509Certificate c = (X509Certificate) cf.generateCertificate(fis); System.out.println("Certficate for " + c.getSubjectDN().getName()); System.out.println("Generated with " + c.getSigAlgName()); System.out.println("== " + c.getSubjectDN().toString()); String publicKey = Base64.encode(c.getPublicKey().getEncoded()); System.out.println("publicKey=" + publicKey); // Map<String, String> map = parseSubjectDN(c.getSubjectDN().toString()); // System.out.println("map: "+map); // String notBefore =c.getNotBefore().toString();//得到开始有效日期 // String notAfter = c.getNotAfter().toString();//得到截止日期 String serialNumber = c.getSerialNumber().toString(16); // 得到序列号 String dn = c.getIssuerDN().getName(); // 得到发行者名 String sigAlgName = c.getSigAlgName(); // 得到签名算法 String algorithm = c.getPublicKey().getAlgorithm(); // 得到公钥算法 SimpleDateFormat intSDF = new SimpleDateFormat("yyyyMMdd"); System.out.println("notBefore=" + intSDF.format(c.getNotBefore())); System.out.println("notAfter=" + intSDF.format(c.getNotAfter())); System.out.println("serialNumber=" + serialNumber); System.out.println("dn=" + dn); System.out.println("sigAlgName=" + sigAlgName); System.out.println("algorithm=" + algorithm); fis.close(); } catch (Exception ex) { ex.printStackTrace(); } }
// 颁发证书 public static MadCertDo issueClientCert( long serialNo, String alias, String cn, String email, String title, Map<String, String> exts, char[] pwd) throws Exception { X500Name subject = X500NameUtil.createClass3EndPrincipal(cn, email, title); KeyPair caKeyPair = CaCertLoader.getClass3CaKeyPair(); KeyPair endKeyPair = KeyPairUtil.generateRSAKeyPair(); X509Certificate endCert = getIns().createClass3EndCert(serialNo, subject, exts, endKeyPair, caKeyPair); MadCertDo madCertDo = new MadCertDo(); madCertDo.setSerialNumber(serialNo); madCertDo.setNotBefore(endCert.getNotBefore()); madCertDo.setNotAfter(endCert.getNotAfter()); madCertDo.setIssuerDN(endCert.getIssuerDN().toString()); madCertDo.setSubjectDN(endCert.getSubjectDN().toString()); madCertDo.setKeyFile(PKCSTransformer.getKeyFileString(endKeyPair.getPrivate(), pwd)); madCertDo.setKeyPwd(String.valueOf(pwd)); return madCertDo; }
public static String getCertificateValidityString(X509Certificate cert, Resources res) { try { cert.checkValidity(); } catch (CertificateExpiredException ce) { return "EXPIRED: "; } catch (CertificateNotYetValidException cny) { return "NOT YET VALID: "; } Date certNotAfter = cert.getNotAfter(); Date now = new Date(); long timeLeft = certNotAfter.getTime() - now.getTime(); // Time left in ms // More than 72h left, display days // More than 3 months display months if (timeLeft > 90l * 24 * 3600 * 1000) { long months = getMonthsDifference(now, certNotAfter); return res.getString(R.string.months_left, months); } else if (timeLeft > 72 * 3600 * 1000) { long days = timeLeft / (24 * 3600 * 1000); return res.getString(R.string.days_left, days); } else { long hours = timeLeft / (3600 * 1000); return res.getString(R.string.hours_left, hours); } }
@Override public void validate(List<X509Certificate> certificateChain, RevocationData revocationData) throws Exception { for (X509Certificate certificate : certificateChain) { LOG.debug("certificate: " + certificate.getSubjectX500Principal()); LOG.debug("validity: " + certificate.getNotBefore() + " - " + certificate.getNotAfter()); } this.trustValidator.isTrusted(certificateChain); }
private String getValidity(X509Certificate certificate) { SimpleDateFormat dateFormat = new SimpleDateFormat("E, d MMM yyyy HH:mm:ss"); return new StringBuilder() .append("Issued On: ") .append(dateFormat.format(certificate.getNotBefore())) .append('\n') .append("Expires On: ") .append(dateFormat.format(certificate.getNotAfter())) .toString(); }
public X509CertificateShortInfo(String alias, X509Certificate cert) { this.alias = alias; if (cert.getIssuerDN() != null) issuer = cert.getIssuerDN().getName(); if (cert.getSubjectDN() != null) subject = cert.getSubjectDN().getName(); algorithm = cert.getSigAlgName(); notBeforeDatetime = cert.getNotBefore(); notAfterDatetime = cert.getNotAfter(); updateViewStyle(); }
/** * Retrieves displayable information about the certificate with the specified index in the chain. * * @param index The index of the certificate to request information on * @return A list of lists of {@link CertificateInformationEntry}s. */ public List<List<CertificateInformationEntry>> getCertificateInfo(final int index) { final List<List<CertificateInformationEntry>> res = new ArrayList<List<CertificateInformationEntry>>(); final X509Certificate cert = chain[index]; List<CertificateInformationEntry> group; boolean tooOld = false, tooNew = false; try { cert.checkValidity(); } catch (CertificateExpiredException ex) { tooOld = true; } catch (CertificateNotYetValidException ex) { tooNew = true; } group = new ArrayList<CertificateInformationEntry>(); group.add( new CertificateInformationEntry( "Valid from", cert.getNotBefore().toString(), tooNew, false)); group.add( new CertificateInformationEntry("Valid to", cert.getNotAfter().toString(), tooOld, false)); res.add(group); final boolean wrongName = index == 0 && !manager.isValidHost(cert); final String names = getAlternateNames(cert); final Map<String, String> fields = CertificateManager.getDNFieldsFromCert(cert); group = new ArrayList<CertificateInformationEntry>(); addCertField(fields, group, "Common name", "CN", wrongName); group.add( new CertificateInformationEntry( "Alternate names", names == null ? NOTPRESENT : names, wrongName, names == null)); addCertField(fields, group, "Organisation", "O", false); addCertField(fields, group, "Unit", "OU", false); addCertField(fields, group, "Locality", "L", false); addCertField(fields, group, "State", "ST", false); addCertField(fields, group, "Country", "C", false); res.add(group); group = new ArrayList<CertificateInformationEntry>(); group.add( new CertificateInformationEntry( "Serial number", cert.getSerialNumber().toString(), false, false)); group.add(new CertificateInformationEntry("Algorithm", cert.getSigAlgName(), false, false)); group.add( new CertificateInformationEntry( "SSL version", String.valueOf(cert.getVersion()), false, false)); res.add(group); return res; }
/* * Initializes the signerInfo and the VerifierInfo from the Certificate Pair */ private void initializeCertificates() { X509Certificate certRoot = null; X509Certificate certIssuer = null; CertificatePair trustedCertificate; if (getFoundCertificate() == null) { CertificatePair[] certs = getRootCertificates(); if (certs.length == 0) return; trustedCertificate = certs[0]; } else { trustedCertificate = getFoundCertificate(); } certRoot = (X509Certificate) trustedCertificate.getRoot(); certIssuer = (X509Certificate) trustedCertificate.getIssuer(); StringBuffer strb = new StringBuffer(); strb.append(issuerString(certIssuer.getSubjectDN())); strb.append("\r\n"); // $NON-NLS-1$ strb.append( NLS.bind( Messages.JarVerificationResult_ValidBetween, (new String[] { dateString(certIssuer.getNotBefore()), dateString(certIssuer.getNotAfter()) }))); strb.append(checkValidity(certIssuer)); signerInfo = strb.toString(); if (certIssuer != null && !certIssuer.equals(certRoot)) { strb = new StringBuffer(); strb.append(issuerString(certIssuer.getIssuerDN())); strb.append("\r\n"); // $NON-NLS-1$ strb.append( NLS.bind( Messages.JarVerificationResult_ValidBetween, (new String[] { dateString(certRoot.getNotBefore()), dateString(certRoot.getNotAfter()) }))); strb.append(checkValidity(certRoot)); verifierInfo = strb.toString(); } }
public static String prettyPrint(X509Certificate x509) { if (x509 == null) throw new IllegalArgumentException("x509 cannot be null"); return String.format( FORMAT, x509.getVersion(), x509.getSerialNumber(), x509.getSigAlgName(), x509.getIssuerX500Principal().getName(), x509.getNotBefore(), x509.getNotAfter(), x509.getSubjectX500Principal().getName(), x509.getPublicKey().getAlgorithm(), x509.getBasicConstraints(), x509.getSigAlgName()); }
private void certDetails(StringBuffer si, X509Certificate c) { SimpleDateFormat validityDateFormater = new SimpleDateFormat("yyyy-MM-dd"); si.append("\n"); si.append(c.getSubjectDN().toString()); si.append("\n"); si.append(validityDateFormater.format(c.getNotBefore())); si.append(" - "); si.append(validityDateFormater.format(c.getNotAfter())); si.append("\nSHA-256: "); si.append(certHash(c, "SHA-256")); si.append("\nSHA-1: "); si.append(certHash(c, "SHA-1")); si.append("\nSigned by: "); si.append(c.getIssuerDN().toString()); si.append("\n"); }
private X509Certificate readCertificate(String certPath) { try { FileInputStream fr = new FileInputStream(certPath); CertificateFactory cf = CertificateFactory.getInstance("X509"); X509Certificate crt = (X509Certificate) cf.generateCertificate(fr); logger.info("Read certificate:"); logger.info("\tCertificate for: " + crt.getSubjectDN()); logger.info("\tCertificate issued by: " + crt.getIssuerDN()); logger.info("\tCertificate is valid from " + crt.getNotBefore() + " to " + crt.getNotAfter()); logger.info("\tCertificate SN# " + crt.getSerialNumber()); logger.info("\tGenerated with " + crt.getSigAlgName()); return crt; } catch (Exception e) { e.printStackTrace(); } return null; }
/* */ private boolean isWorthTrying( X509Certificate paramX509Certificate1, X509Certificate paramX509Certificate2) /* */ { /* 220 */ boolean bool = false; /* */ /* 222 */ if (debug != null) { /* 223 */ debug.println( "PKIXCertPathValidator.isWorthTrying() checking if this trusted cert is worth trying ..."); /* */ } /* */ /* 227 */ if (paramX509Certificate2 == null) { /* 228 */ return true; /* */ } /* */ /* 231 */ AdaptableX509CertSelector localAdaptableX509CertSelector = new AdaptableX509CertSelector(); /* */ /* 235 */ localAdaptableX509CertSelector.setSubject( paramX509Certificate2.getIssuerX500Principal()); /* */ /* 238 */ localAdaptableX509CertSelector.setValidityPeriod( paramX509Certificate2.getNotBefore(), paramX509Certificate2.getNotAfter()); /* */ try /* */ { /* 246 */ X509CertImpl localX509CertImpl = X509CertImpl.toImpl(paramX509Certificate2); /* 247 */ localAdaptableX509CertSelector.parseAuthorityKeyIdentifierExtension( localX509CertImpl.getAuthorityKeyIdentifierExtension()); /* */ /* 250 */ bool = localAdaptableX509CertSelector.match(paramX509Certificate1); /* */ } /* */ catch (Exception localException) /* */ { /* */ } /* 255 */ if (debug != null) { /* 256 */ if (bool) /* 257 */ debug.println("YES - try this trustedCert"); /* */ else { /* 259 */ debug.println("NO - don't try this trustedCert"); /* */ } /* */ } /* */ /* 263 */ return bool; /* */ }
/** * Load an X509 Cert from a file and add it to the trusted set of certificates in the key store * * @return success * @since 0.8.2, moved from SSLEepGet in 0.9.9 */ public static boolean addCert(File file, String alias, KeyStore ks) { InputStream fis = null; try { fis = new FileInputStream(file); CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate cert = (X509Certificate) cf.generateCertificate(fis); info( "Read X509 Certificate from " + file.getAbsolutePath() + " Issuer: " + cert.getIssuerX500Principal() + "; Valid From: " + cert.getNotBefore() + " To: " + cert.getNotAfter()); try { cert.checkValidity(); } catch (CertificateExpiredException cee) { error("Rejecting expired X509 Certificate: " + file.getAbsolutePath(), cee); return false; } catch (CertificateNotYetValidException cnyve) { error("Rejecting X509 Certificate not yet valid: " + file.getAbsolutePath(), cnyve); return false; } ks.setCertificateEntry(alias, cert); info("Now trusting X509 Certificate, Issuer: " + cert.getIssuerX500Principal()); } catch (GeneralSecurityException gse) { error("Error reading X509 Certificate: " + file.getAbsolutePath(), gse); return false; } catch (IOException ioe) { error("Error reading X509 Certificate: " + file.getAbsolutePath(), ioe); return false; } finally { try { if (fis != null) fis.close(); } catch (IOException foo) { } } return true; }
public Set findCRLs( X509CRLStoreSelector crlselect, ExtendedPKIXParameters paramsPKIX, Date currentDate) throws AnnotatedException { Set initialSet = new HashSet(); // get complete CRL(s) try { initialSet.addAll(findCRLs(crlselect, paramsPKIX.getAdditionalStores())); initialSet.addAll(findCRLs(crlselect, paramsPKIX.getStores())); initialSet.addAll(findCRLs(crlselect, paramsPKIX.getCertStores())); } catch (AnnotatedException e) { throw new AnnotatedException("Exception obtaining complete CRLs.", e); } Set finalSet = new HashSet(); Date validityDate = currentDate; if (paramsPKIX.getDate() != null) { validityDate = paramsPKIX.getDate(); } // based on RFC 5280 6.3.3 for (Iterator it = initialSet.iterator(); it.hasNext(); ) { X509CRL crl = (X509CRL) it.next(); if (crl.getNextUpdate().after(validityDate)) { X509Certificate cert = crlselect.getCertificateChecking(); if (cert != null) { if (crl.getThisUpdate().before(cert.getNotAfter())) { finalSet.add(crl); } } else { finalSet.add(crl); } } } return finalSet; }
private void logKeyStore(KeyStore store) throws KeyStoreException { LOG.trace("Certificates count: " + store.size()); Enumeration aliases = store.aliases(); while (aliases.hasMoreElements()) { String alias = (String) aliases.nextElement(); Certificate[] certs = store.getCertificateChain(alias); if (certs != null) { LOG.debug("Certificate chain '" + alias + "':"); for (int c = 0; c < certs.length; c++) { if (certs[c] instanceof X509Certificate) { X509Certificate cert = (X509Certificate) certs[c]; LOG.trace(" Certificate " + (c + 1) + ":"); LOG.trace(" Subject DN: " + cert.getSubjectDN()); LOG.trace(" Signature Algorithm: " + cert.getSigAlgName()); LOG.trace(" Valid from: " + cert.getNotBefore()); LOG.trace(" Valid until: " + cert.getNotAfter()); LOG.trace(" Issuer: " + cert.getIssuerDN()); } } } } }
@RequestMapping(value = "/pos-info", method = RequestMethod.GET) public String listReport(ModelMap modelMap) throws Exception { ClassPathResource resource = new ClassPathResource("server-configuration.properties"); Properties properties = PropertiesLoaderUtils.loadProperties(resource); modelMap.addAttribute("modoIntegracion", properties.getProperty("pos.server.modo")); String puntoEmision = properties.getProperty("pos.server.punto_emision"); modelMap.addAttribute("puntoEmision", puntoEmision); String MAC = macService.getCachedMAC(); modelMap.addAttribute("MAC", MAC); String transferencia = properties.getProperty("pos.server.transferencia"); modelMap.addAttribute("transferenciaHabilitada", transferencia.equals("1")); String limpieza = properties.getProperty("pos.server.limpieza"); modelMap.addAttribute("limpiezaHabilitada", limpieza.equals("1")); String storePath = properties.getProperty("pos.server.almacenfirma.archivo"); String storePassword = properties.getProperty("pos.server.almacenfirma.password"); String certAlias = properties.getProperty("pos.server.certificado.alias"); Init.init(); KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(getClass().getResourceAsStream(storePath), storePassword.toCharArray()); X509Certificate certificate = (X509Certificate) keyStore.getCertificate(certAlias); DateTime expireCertDate = new DateTime(certificate.getNotAfter()); DateTime now = DateTime.now(); int difference = Days.daysBetween(expireCertDate, now).getDays(); modelMap.addAttribute("certificadoExpirado", (difference > 0)); modelMap.addAttribute("fechaExpiracion", expireCertDate); return "/page"; }
public static String toString(X509Certificate cert, boolean htmlStyle) { String cn = getCN(cert); String startStart = DF.format(cert.getNotBefore()); String endDate = DF.format(cert.getNotAfter()); String subject = JavaImpl.getSubjectX500(cert); String issuer = JavaImpl.getIssuerX500(cert); Iterator crls = getCRLs(cert).iterator(); if (subject.equals(issuer)) { issuer = "self-signed"; } StringBuffer buf = new StringBuffer(128); if (htmlStyle) { buf.append("<strong class=\"cn\">"); } buf.append(cn); if (htmlStyle) { buf.append("</strong>"); } buf.append(LINE_ENDING); buf.append("Valid: "); buf.append(startStart); buf.append(" - "); buf.append(endDate); buf.append(LINE_ENDING); buf.append("s: "); buf.append(subject); buf.append(LINE_ENDING); buf.append("i: "); buf.append(issuer); while (crls.hasNext()) { buf.append(LINE_ENDING); buf.append("CRL: "); buf.append((String) crls.next()); } buf.append(LINE_ENDING); return buf.toString(); }
/** @return Date -> Validate ends date */ public Date getAfterDate() { return certificate.getNotAfter(); }
public X509CRL updateCRL(CRLEntry[] entries) throws Exception { crl = CertUtil.createCRL(cert, key, entries, cert.getNotAfter()); return crl; }
public X509CRL updateCRL(CRLEntry entry) throws Exception { CRLEntry[] entries = new CRLEntry[1]; entries[0] = entry; crl = CertUtil.createCRL(cert, key, entries, cert.getNotAfter()); return crl; }
/** * Appends an HTML representation of the given X509Certificate. * * @param sb StringBuilder to append to * @param certificate to print */ private void renderX509(StringBuilder sb, X509Certificate certificate) { X500Principal issuer = certificate.getIssuerX500Principal(); X500Principal subject = certificate.getSubjectX500Principal(); sb.append("<table cellspacing='1' cellpadding='1'>\n"); // subject addTitle(sb, R.getI18NString("service.gui.CERT_INFO_ISSUED_TO")); try { for (Rdn name : new LdapName(subject.getName()).getRdns()) { String nameType = name.getType(); String lblKey = "service.gui.CERT_INFO_" + nameType; String lbl = R.getI18NString(lblKey); if ((lbl == null) || ("!" + lblKey + "!").equals(lbl)) lbl = nameType; final String value; Object nameValue = name.getValue(); if (nameValue instanceof byte[]) { byte[] nameValueAsByteArray = (byte[]) nameValue; value = getHex(nameValueAsByteArray) + " (" + new String(nameValueAsByteArray) + ")"; } else value = nameValue.toString(); addField(sb, lbl, value); } } catch (InvalidNameException ine) { addField(sb, R.getI18NString("service.gui.CERT_INFO_CN"), subject.getName()); } // issuer addTitle(sb, R.getI18NString("service.gui.CERT_INFO_ISSUED_BY")); try { for (Rdn name : new LdapName(issuer.getName()).getRdns()) { String nameType = name.getType(); String lblKey = "service.gui.CERT_INFO_" + nameType; String lbl = R.getI18NString(lblKey); if ((lbl == null) || ("!" + lblKey + "!").equals(lbl)) lbl = nameType; final String value; Object nameValue = name.getValue(); if (nameValue instanceof byte[]) { byte[] nameValueAsByteArray = (byte[]) nameValue; value = getHex(nameValueAsByteArray) + " (" + new String(nameValueAsByteArray) + ")"; } else value = nameValue.toString(); addField(sb, lbl, value); } } catch (InvalidNameException ine) { addField(sb, R.getI18NString("service.gui.CERT_INFO_CN"), issuer.getName()); } // validity addTitle(sb, R.getI18NString("service.gui.CERT_INFO_VALIDITY")); addField( sb, R.getI18NString("service.gui.CERT_INFO_ISSUED_ON"), certificate.getNotBefore().toString()); addField( sb, R.getI18NString("service.gui.CERT_INFO_EXPIRES_ON"), certificate.getNotAfter().toString()); addTitle(sb, R.getI18NString("service.gui.CERT_INFO_FINGERPRINTS")); try { String sha1String = getThumbprint(certificate, "SHA1"); String md5String = getThumbprint(certificate, "MD5"); addField(sb, "SHA1:", sha1String); addField(sb, "MD5:", md5String); } catch (CertificateException e) { // do nothing as we cannot show this value } addTitle(sb, R.getI18NString("service.gui.CERT_INFO_CERT_DETAILS")); addField( sb, R.getI18NString("service.gui.CERT_INFO_SER_NUM"), certificate.getSerialNumber().toString()); addField( sb, R.getI18NString("service.gui.CERT_INFO_VER"), String.valueOf(certificate.getVersion())); addField( sb, R.getI18NString("service.gui.CERT_INFO_SIGN_ALG"), String.valueOf(certificate.getSigAlgName())); addTitle(sb, R.getI18NString("service.gui.CERT_INFO_PUB_KEY_INFO")); addField( sb, R.getI18NString("service.gui.CERT_INFO_ALG"), certificate.getPublicKey().getAlgorithm()); if (certificate.getPublicKey().getAlgorithm().equals("RSA")) { RSAPublicKey key = (RSAPublicKey) certificate.getPublicKey(); addField( sb, R.getI18NString("service.gui.CERT_INFO_PUB_KEY"), R.getI18NString( "service.gui.CERT_INFO_KEY_BYTES_PRINT", new String[] { String.valueOf(key.getModulus().toByteArray().length - 1), key.getModulus().toString(16) })); addField( sb, R.getI18NString("service.gui.CERT_INFO_EXP"), key.getPublicExponent().toString()); addField( sb, R.getI18NString("service.gui.CERT_INFO_KEY_SIZE"), R.getI18NString( "service.gui.CERT_INFO_KEY_BITS_PRINT", new String[] {String.valueOf(key.getModulus().bitLength())})); } else if (certificate.getPublicKey().getAlgorithm().equals("DSA")) { DSAPublicKey key = (DSAPublicKey) certificate.getPublicKey(); addField(sb, "Y:", key.getY().toString(16)); } addField( sb, R.getI18NString("service.gui.CERT_INFO_SIGN"), R.getI18NString( "service.gui.CERT_INFO_KEY_BYTES_PRINT", new String[] { String.valueOf(certificate.getSignature().length), getHex(certificate.getSignature()) })); sb.append("</table>\n"); }
// controlla che il certificato del firmatario sia affidabile controllando la sua catena di // certificati // valida il certificato X509 del firmatario usando il built-in PKIX support messo a disposizione // da java // caricando il keystore contenente i certificati degli enti certificatori autorizzati dallo stato // italiano private PKIXCertPathBuilderResult isTrustedSigner(SignerInformation signer) throws FirmapiuException { // genera la lista di certificati da controllare per generare la catena dei certificati del // firmatario // TODO quali certificati carica esattamente? Collection<?> certCollection = certStore.getMatches(signer.getSID()); Iterator<?> certIt = certCollection.iterator(); X509CertificateHolder cert = (X509CertificateHolder) certIt.next(); List<X509Certificate> chain = new LinkedList<X509Certificate>(); JcaX509CertificateConverter certConverter = new JcaX509CertificateConverter().setProvider(this.bcProvName); try { X509Certificate x509cert = certConverter.getCertificate(cert); chain.add(x509cert); while (certIt.hasNext()) { x509cert = certConverter.getCertificate((X509CertificateHolder) certIt.next()); chain.add(x509cert); } } catch (CertificateException e) { new FirmapiuException(CERT_DEFAULT_ERROR, e); } // carica i certificati presenti nel token crittografico passato come parametro KeyStore anchors = this.token.loadKeyStore(null); X509CertSelector target = new X509CertSelector(); target.setCertificate(chain.get(0)); PKIXBuilderParameters params; CertPathBuilder builder; try { params = new PKIXBuilderParameters(anchors, target); // disabilita il controllo delle CRL params.setRevocationEnabled(false); // se il certificato è scaduto cerca di generare lo stesso la catena dei certificati try { X509Certificate x509cert = certConverter.getCertificate(cert); // long before=x509cert.getNotBefore().getTime(); long after = x509cert.getNotAfter().getTime(); after -= 10; params.setDate(new Date(after)); } catch (CertificateException e) { throw new FirmapiuException(CERT_KEYSTORE_DEFAULT_ERROR, e); } CertStoreParameters intermediates = new CollectionCertStoreParameters(chain); params.addCertStore(CertStore.getInstance("Collection", intermediates)); params.setSigProvider(this.bcProvName); builder = CertPathBuilder.getInstance("PKIX", this.bcProvName); } catch (KeyStoreException | InvalidAlgorithmParameterException e) { throw new FirmapiuException(CERT_KEYSTORE_DEFAULT_ERROR, e); } catch (NoSuchAlgorithmException | NoSuchProviderException e) { throw new FirmapiuException(DEFAULT_ERROR, e); } /* * If build() returns successfully, the certificate is valid. More details * about the valid path can be obtained through the PKIXBuilderResult. * If no valid path can be found, a CertPathBuilderException is thrown. */ try { return (PKIXCertPathBuilderResult) builder.build(params); } catch (CertPathBuilderException e) { throw new FirmapiuException(VERIFY_SIGNER_CERTPATH_ERROR, e); } catch (InvalidAlgorithmParameterException e) { throw new FirmapiuException(DEFAULT_ERROR, e); } } // fine metodo
private AlfrescoRuntimeException signFile( final NodeRef nodeRefToSign, final DigitalSigningDTO signingDTO, final File alfTempDir, final String alias, final KeyStore ks, final PrivateKey key, final Certificate[] chain) { final String fileNameToSign = fileFolderService.getFileInfo(nodeRefToSign).getName(); File fileConverted = null; File tempDir = null; try { ContentReader fileToSignContentReader = getReader(nodeRefToSign); if (fileToSignContentReader != null) { String newName = null; // Check if document is PDF or transform it if (!MimetypeMap.MIMETYPE_PDF.equals(fileToSignContentReader.getMimetype())) { // Transform document in PDF document final ContentTransformer tranformer = contentTransformerRegistry.getTransformer( fileToSignContentReader.getMimetype(), fileToSignContentReader.getSize(), MimetypeMap.MIMETYPE_PDF, new TransformationOptions()); if (tranformer != null) { tempDir = new File(alfTempDir.getPath() + File.separatorChar + nodeRefToSign.getId()); if (tempDir != null) { tempDir.mkdir(); fileConverted = new File(tempDir, fileNameToSign + "_" + System.currentTimeMillis() + ".pdf"); if (fileConverted != null) { final ContentWriter newDoc = new FileContentWriter(fileConverted); if (newDoc != null) { newDoc.setMimetype(MimetypeMap.MIMETYPE_PDF); tranformer.transform(fileToSignContentReader, newDoc); fileToSignContentReader = new FileContentReader(fileConverted); final String originalName = (String) nodeService.getProperty(nodeRefToSign, ContentModel.PROP_NAME); newName = originalName.substring(0, originalName.lastIndexOf(".")) + ".pdf"; } } } } else { log.error( "[" + fileNameToSign + "] No suitable converter found to convert the document in PDF."); return new AlfrescoRuntimeException( "[" + fileNameToSign + "] No suitable converter found to convert the document in PDF."); } } // Convert PDF in PDF/A format final File pdfAFile = convertPdfToPdfA(fileToSignContentReader.getContentInputStream()); final PdfReader reader = new PdfReader(new FileInputStream(pdfAFile)); if (nodeRefToSign != null) { tempDir = new File(alfTempDir.getPath() + File.separatorChar + nodeRefToSign.getId()); if (tempDir != null) { tempDir.mkdir(); final File file = new File(tempDir, fileNameToSign); if (file != null) { final FileOutputStream fout = new FileOutputStream(file); final PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0'); if (stp != null) { final PdfSignatureAppearance sap = stp.getSignatureAppearance(); if (sap != null) { sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED); sap.setReason(signingDTO.getSignReason()); sap.setLocation(signingDTO.getSignLocation()); sap.setContact(signingDTO.getSignContact()); sap.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED); sap.setImageScale(1); // digital signature if (signingDTO.getSigningField() != null && !signingDTO.getSigningField().trim().equalsIgnoreCase("")) { Image img = null; if (signingDTO.getImage() != null) { final ContentReader imageContentReader = getReader(signingDTO.getImage()); final AcroFields af = reader.getAcroFields(); if (af != null) { final List<FieldPosition> positions = af.getFieldPositions(signingDTO.getSigningField()); if (positions != null && positions.size() > 0 && positions.get(0) != null && positions.get(0).position != null) { final BufferedImage newImg = scaleImage( ImageIO.read(imageContentReader.getContentInputStream()), BufferedImage.TYPE_INT_RGB, Float.valueOf(positions.get(0).position.getWidth()).intValue(), Float.valueOf(positions.get(0).position.getHeight()).intValue()); img = Image.getInstance(newImg, null); } else { log.error( "[" + fileNameToSign + "] The field '" + signingDTO.getSigningField() + "' doesn't exist in the document."); return new AlfrescoRuntimeException( "[" + fileNameToSign + "] The field '" + signingDTO.getSigningField() + "' doesn't exist in the document."); } } if (img == null) { img = Image.getInstance( ImageIO.read(imageContentReader.getContentInputStream()), null); } sap.setImage(img); } sap.setVisibleSignature(signingDTO.getSigningField()); } else { int pageToSign = 1; if (DigitalSigningDTO.PAGE_LAST.equalsIgnoreCase( signingDTO.getPages().trim())) { pageToSign = reader.getNumberOfPages(); } else if (DigitalSigningDTO.PAGE_SPECIFIC.equalsIgnoreCase( signingDTO.getPages().trim())) { if (signingDTO.getPageNumber() > 0 && signingDTO.getPageNumber() <= reader.getNumberOfPages()) { pageToSign = signingDTO.getPageNumber(); } else { throw new AlfrescoRuntimeException("Page number is out of bound."); } } if (signingDTO.getImage() != null) { final ContentReader imageContentReader = getReader(signingDTO.getImage()); // Resize image final BufferedImage newImg = scaleImage( ImageIO.read(imageContentReader.getContentInputStream()), BufferedImage.TYPE_INT_RGB, signingDTO.getSignWidth(), signingDTO.getSignHeight()); final Image img = Image.getInstance(newImg, null); sap.setImage(img); } if (signingDTO.getPosition() != null && !DigitalSigningDTO.POSITION_CUSTOM.equalsIgnoreCase( signingDTO.getPosition().trim())) { final Rectangle pageRect = reader.getPageSizeWithRotation(1); sap.setVisibleSignature( positionSignature( signingDTO.getPosition(), pageRect, signingDTO.getSignWidth(), signingDTO.getSignHeight(), signingDTO.getxMargin(), signingDTO.getyMargin()), pageToSign, null); } else { sap.setVisibleSignature( new Rectangle( signingDTO.getLocationX(), signingDTO.getLocationY(), signingDTO.getLocationX() + signingDTO.getSignWidth(), signingDTO.getLocationY() - signingDTO.getSignHeight()), pageToSign, null); } } stp.close(); NodeRef destinationNode = null; NodeRef originalDoc = null; boolean addAsNewVersion = false; if (signingDTO.getDestinationFolder() == null) { destinationNode = nodeRefToSign; nodeService.addAspect(destinationNode, ContentModel.ASPECT_VERSIONABLE, null); addAsNewVersion = true; } else { originalDoc = nodeRefToSign; destinationNode = createDestinationNode( file.getName(), signingDTO.getDestinationFolder(), nodeRefToSign); } if (destinationNode != null) { final ContentWriter writer = contentService.getWriter(destinationNode, ContentModel.PROP_CONTENT, true); if (writer != null) { writer.setEncoding(fileToSignContentReader.getEncoding()); writer.setMimetype("application/pdf"); writer.putContent(file); file.delete(); if (fileConverted != null) { fileConverted.delete(); } nodeService.addAspect( destinationNode, SigningModel.ASPECT_SIGNED, new HashMap<QName, Serializable>()); nodeService.setProperty( destinationNode, SigningModel.PROP_REASON, signingDTO.getSignReason()); nodeService.setProperty( destinationNode, SigningModel.PROP_LOCATION, signingDTO.getSignLocation()); nodeService.setProperty( destinationNode, SigningModel.PROP_SIGNATUREDATE, new java.util.Date()); nodeService.setProperty( destinationNode, SigningModel.PROP_SIGNEDBY, AuthenticationUtil.getRunAsUser()); if (newName != null) { nodeService.setProperty(destinationNode, ContentModel.PROP_NAME, newName); } final X509Certificate c = (X509Certificate) ks.getCertificate(alias); nodeService.setProperty( destinationNode, SigningModel.PROP_VALIDITY, c.getNotAfter()); nodeService.setProperty( destinationNode, SigningModel.PROP_ORIGINAL_DOC, originalDoc); if (!addAsNewVersion) { if (!nodeService.hasAspect(originalDoc, SigningModel.ASPECT_ORIGINAL_DOC)) { nodeService.addAspect( originalDoc, SigningModel.ASPECT_ORIGINAL_DOC, new HashMap<QName, Serializable>()); } nodeService.createAssociation( originalDoc, destinationNode, SigningModel.PROP_RELATED_DOC); } } } else { log.error("[" + fileNameToSign + "] Destination node is not a valid NodeRef."); return new AlfrescoRuntimeException( "[" + fileNameToSign + "] Destination node is not a valid NodeRef."); } } else { log.error("[" + fileNameToSign + "] Unable to get PDF appearance signature."); return new AlfrescoRuntimeException( "[" + fileNameToSign + "] Unable to get PDF appearance signature."); } } else { log.error("[" + fileNameToSign + "] Unable to create PDF signature."); return new AlfrescoRuntimeException( "[" + fileNameToSign + "] Unable to create PDF signature."); } } } } else { log.error("[" + fileNameToSign + "] Unable to get document to sign content."); return new AlfrescoRuntimeException( "[" + fileNameToSign + "] Unable to get document to sign content."); } if (pdfAFile != null) { pdfAFile.delete(); } return null; } else { log.error("[" + fileNameToSign + "] The document has no content."); return new AlfrescoRuntimeException( "[" + fileNameToSign + "] The document has no content."); } } catch (KeyStoreException e) { log.error("[" + fileNameToSign + "] " + e); return new AlfrescoRuntimeException("[" + fileNameToSign + "] " + e.getMessage(), e); } catch (ContentIOException e) { log.error("[" + fileNameToSign + "] " + e); return new AlfrescoRuntimeException("[" + fileNameToSign + "] " + e.getMessage(), e); } catch (IOException e) { log.error("[" + fileNameToSign + "] " + e); return new AlfrescoRuntimeException("[" + fileNameToSign + "] " + e.getMessage(), e); } catch (DocumentException e) { log.error("[" + fileNameToSign + "] " + e); return new AlfrescoRuntimeException("[" + fileNameToSign + "] " + e.getMessage(), e); } finally { if (tempDir != null) { try { tempDir.delete(); } catch (Exception ex) { log.error("[" + fileNameToSign + "] " + ex); return new AlfrescoRuntimeException("[" + fileNameToSign + "] " + ex.getMessage(), ex); } } } }
/** * Recupera la fecha de expiración del certificado en formato "yyyy-MM-dd". * * @param cert Certificado. * @return Fecha de caducidad. */ private static String getExpiredDate(final X509Certificate cert) { return new SimpleDateFormat("yyyy-MM-dd").format(cert.getNotAfter()); // $NON-NLS-1$ }
public TimeTool getValidUntil() { Date val = cert.getNotAfter(); TimeTool ret = new TimeTool(val.getTime()); return ret; }