List of usage examples for java.security.cert X509Certificate getNotBefore
public abstract Date getNotBefore();
From source file:com.jrummyapps.busybox.signing.ZipSigner.java
/** * Tool to sign JAR files (including APKs and OTA updates) in a way compatible with the mincrypt verifier, using * SHA1 and RSA keys.// w w w . j ava2 s .c o m * * @param unsignedZip * The path to the APK, ZIP, JAR to sign * @param destination * The output file * @return true if successfully signed the file */ public static boolean signZip(File unsignedZip, File destination) { final AssetManager am = App.getContext().getAssets(); JarArchiveOutputStream outputJar = null; JarFile inputJar = null; try { X509Certificate publicKey = readPublicKey(am.open(PUBLIC_KEY)); PrivateKey privateKey = readPrivateKey(am.open(PRIVATE_KEY)); // Assume the certificate is valid for at least an hour. long timestamp = publicKey.getNotBefore().getTime() + 3600L * 1000; inputJar = new JarFile(unsignedZip, false); // Don't verify. FileOutputStream stream = new FileOutputStream(destination); outputJar = new JarArchiveOutputStream(stream); outputJar.setLevel(9); // MANIFEST.MF Manifest manifest = addDigestsToManifest(inputJar); JarArchiveEntry je = new JarArchiveEntry(JarFile.MANIFEST_NAME); je.setTime(timestamp); outputJar.putArchiveEntry(je); manifest.write(outputJar); ZipSignature signature1 = new ZipSignature(); signature1.initSign(privateKey); ByteArrayOutputStream out = new ByteArrayOutputStream(); writeSignatureFile(manifest, out); // CERT.SF Signature signature = Signature.getInstance("SHA1withRSA"); signature.initSign(privateKey); je = new JarArchiveEntry(CERT_SF_NAME); je.setTime(timestamp); outputJar.putArchiveEntry(je); byte[] sfBytes = writeSignatureFile(manifest, new SignatureOutputStream(outputJar, signature)); signature1.update(sfBytes); byte[] signatureBytes = signature1.sign(); // CERT.RSA je = new JarArchiveEntry(CERT_RSA_NAME); je.setTime(timestamp); outputJar.putArchiveEntry(je); outputJar.write(readContentAsBytes(am.open(TEST_KEY))); outputJar.write(signatureBytes); copyFiles(manifest, inputJar, outputJar, timestamp); } catch (Exception e) { Crashlytics.logException(e); return false; } finally { IOUtils.closeQuietly(inputJar); IOUtils.closeQuietly(outputJar); } return true; }
From source file:wptools.cmds.DumpCerts.java
private static void dumpCert(X509Certificate cert) { System.out.println("Serial No.: " + formatFing(cert.getSerialNumber().toByteArray())); try {//from w w w .j a v a 2 s .com for (String ftype : FTYPES) { MessageDigest md = MessageDigest.getInstance(ftype); md.reset(); System.out.format("%s: %s%n", ftype, formatFing(md.digest(cert.getEncoded()))); } } catch (NoSuchAlgorithmException | CertificateException e) { Misc.die(e.getMessage()); } System.out.println("Issued To: " + cert.getSubjectX500Principal()); System.out.println("Issued By: " + cert.getIssuerX500Principal()); System.out.format("Valid: from %tFT%<tT%<tz to %tFT%<tT%<tz%n%n", cert.getNotBefore(), cert.getNotAfter()); }
From source file:com.dbay.apns4j.tools.ApnsTools.java
public final static SocketFactory createSocketFactory(InputStream keyStore, String password, String keystoreType, String algorithm, String protocol) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException, KeyManagementException, CertificateExpiredException { char[] pwdChars = password.toCharArray(); KeyStore ks = KeyStore.getInstance(keystoreType); ks.load(keyStore, pwdChars);/*from w w w. j ava 2s.c o m*/ // ?? Enumeration<String> enums = ks.aliases(); String alias = ""; if (enums.hasMoreElements()) { alias = enums.nextElement(); } if (StringUtils.isNotEmpty(alias)) { X509Certificate certificate = (X509Certificate) ks.getCertificate(alias); if (null != certificate) { String type = certificate.getType(); int ver = certificate.getVersion(); String name = certificate.getSubjectDN().getName(); String serialNumber = certificate.getSerialNumber().toString(16); String issuerDN = certificate.getIssuerDN().getName(); String sigAlgName = certificate.getSigAlgName(); String publicAlgorithm = certificate.getPublicKey().getAlgorithm(); Date before = certificate.getNotBefore(); Date after = certificate.getNotAfter(); String beforeStr = DateFormatUtils.format(before, "yyyy-MM-dd HH:mm:ss"); String afterStr = DateFormatUtils.format(after, "yyyy-MM-dd HH:mm:ss"); // ?? long expire = DateUtil.getNumberOfDaysBetween(new Date(), after); if (expire <= 0) { if (LOG.isErrorEnabled()) { LOG.error( "?[{}], [{}], ?[{}], ??[{}], ?[{}], ??[{}], [{}], [{}][{}], ?[{}]", name, type, ver, serialNumber, issuerDN, sigAlgName, publicAlgorithm, beforeStr, afterStr, Math.abs(expire)); } throw new CertificateExpiredException("??[" + Math.abs(expire) + "]"); } if (LOG.isInfoEnabled()) { LOG.info( "?[{}], [{}], ?[{}], ??[{}], ?[{}], ??[{}], [{}], [{}][{}], ?[{}]?", name, type, ver, serialNumber, issuerDN, sigAlgName, publicAlgorithm, beforeStr, afterStr, expire); } } } KeyManagerFactory kf = KeyManagerFactory.getInstance(algorithm); kf.init(ks, pwdChars); TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm); tmf.init((KeyStore) null); SSLContext context = SSLContext.getInstance(protocol); context.init(kf.getKeyManagers(), tmf.getTrustManagers(), null); return context.getSocketFactory(); }
From source file:com.vmware.identity.idm.ValidateUtil.java
/** * Validates that given certificate is <code>valid</code>. * clockTolerance - value of current clock tolerance in milliseconds * @throws IllegalArgumentException/*from w w w . jav a 2 s. com*/ * on validation failure */ public static void validateSolutionDetail(SolutionDetail fieldValue, String fieldName, long clockTolerance) { X509Certificate cert = fieldValue.getCertificate(); ValidateUtil.validateNotNull(cert, "Solution user certificate"); try { cert.checkValidity(); } catch (CertificateException ex) { if (ex instanceof CertificateNotYetValidException) { // Check to see whether certificate is within clock tolerance // if so do not throw, cert passes the validation if (cert.getNotBefore().getTime() <= System.currentTimeMillis() + clockTolerance) { return; } } if (ex instanceof CertificateExpiredException) { // Check to see whether certificate is within clock tolerance // if so do not throw, cert passes the validation if (cert.getNotAfter().getTime() >= System.currentTimeMillis() - clockTolerance) { return; } } logAndThrow(String.format("'%s' certificate is invalid - " + "certificateException %s", fieldName, ex.toString())); } }
From source file:org.wso2.carbon.certificate.mgt.core.impl.CertificateGenerator.java
public static void extractCertificateDetails(byte[] certificateBytes, CertificateResponse certificateResponse) throws CertificateManagementDAOException { try {/*from w ww . j a va 2s . c o m*/ if (certificateBytes != null) { java.security.cert.Certificate x509Certificate = (java.security.cert.Certificate) Serializer .deserialize(certificateBytes); if (x509Certificate instanceof X509Certificate) { X509Certificate certificate = (X509Certificate) x509Certificate; certificateResponse.setNotAfter(certificate.getNotAfter().getTime()); certificateResponse.setNotBefore(certificate.getNotBefore().getTime()); certificateResponse.setCertificateserial(certificate.getSerialNumber()); certificateResponse.setIssuer(certificate.getIssuerDN().getName()); certificateResponse.setSubject(certificate.getSubjectDN().getName()); certificateResponse.setCertificateVersion(certificate.getVersion()); } } } catch (ClassNotFoundException | IOException e) { String errorMsg = "Error while during deserialization of the certificate."; throw new CertificateManagementDAOException(errorMsg, e); } }
From source file:com.xwiki.authentication.sts.STSTokenValidator.java
/** * validateToken(SignableSAMLObject samlToken) * Validates Token from SAMLlObject - returns boolen * Validates Token - exitracting sertificate from samlToken. * And validates it. Returning true or false according on validation results. * @param samlToken SignableSAMLObject//from ww w .ja v a 2 s. com * @return boolean valid => true, not valid => false */ private static boolean validateToken(SignableSAMLObject samlToken) throws SecurityException, ValidationException, ConfigurationException, UnmarshallingException, CertificateException, KeyException { // Validate XML structure samlToken.validate(true); Signature signature = samlToken.getSignature(); X509Certificate certificate = certFromToken(samlToken); // Certificate data log.debug("certificate issuerDN: " + certificate.getIssuerDN()); log.debug("certificate issuerUniqueID: " + certificate.getIssuerUniqueID()); log.debug("certificate issuerX500Principal: " + certificate.getIssuerX500Principal()); log.debug("certificate notBefore: " + certificate.getNotBefore()); log.debug("certificate notAfter: " + certificate.getNotAfter()); log.debug("certificate serialNumber: " + certificate.getSerialNumber()); log.debug("certificate sigAlgName: " + certificate.getSigAlgName()); log.debug("certificate sigAlgOID: " + certificate.getSigAlgOID()); log.debug("certificate signature: " + new String(certificate.getSignature())); log.debug("certificate issuerX500Principal: " + certificate.getIssuerX500Principal().toString()); log.debug("certificate publicKey: " + certificate.getPublicKey()); log.debug("certificate subjectDN: " + certificate.getSubjectDN()); log.debug("certificate sigAlgOID: " + certificate.getSigAlgOID()); log.debug("certificate version: " + certificate.getVersion()); BasicX509Credential cred = new BasicX509Credential(); cred.setEntityCertificate(certificate); // Credential data cred.setEntityId(entityId); log.debug("cred entityId: " + cred.getEntityId()); log.debug("cred usageType: " + cred.getUsageType()); log.debug("cred credentalContextSet: " + cred.getCredentalContextSet()); log.debug("cred hashCode: " + cred.hashCode()); log.debug("cred privateKey: " + cred.getPrivateKey()); log.debug("cred publicKey: " + cred.getPublicKey()); log.debug("cred secretKey: " + cred.getSecretKey()); log.debug("cred entityCertificateChain: " + cred.getEntityCertificateChain()); ArrayList<Credential> trustedCredentials = new ArrayList<Credential>(); trustedCredentials.add(cred); CollectionCredentialResolver credResolver = new CollectionCredentialResolver(trustedCredentials); KeyInfoCredentialResolver kiResolver = SecurityTestHelper.buildBasicInlineKeyInfoResolver(); ExplicitKeySignatureTrustEngine engine = new ExplicitKeySignatureTrustEngine(credResolver, kiResolver); CriteriaSet criteriaSet = new CriteriaSet(); criteriaSet.add(new EntityIDCriteria(entityId)); Base64 decoder = new Base64(); // In trace mode write certificate in the file if (log.isTraceEnabled()) { String certEncoded = new String(decoder.encode(certificate.getEncoded())); try { FileUtils.writeStringToFile(new File("/tmp/Certificate.cer"), "-----BEGIN CERTIFICATE-----\n" + certEncoded + "\n-----END CERTIFICATE-----"); log.trace("Certificate file was saved in: /tmp/Certificate.cer"); } catch (IOException e1) { log.error(e1); } } return engine.validate(signature, criteriaSet); }
From source file:org.digidoc4j.impl.bdoc.xades.validation.TimemarkSignatureValidator.java
private void addCertificateExpirationError() { Date signingTime = signature.getTrustedSigningTime(); if (signingTime == null) { return;/*w w w. j a v a 2s. c o m*/ } X509Certificate signerCert = signature.getSigningCertificate().getX509Certificate(); Date notBefore = signerCert.getNotBefore(); Date notAfter = signerCert.getNotAfter(); boolean isCertValid = signingTime.compareTo(notBefore) >= 0 && signingTime.compareTo(notAfter) <= 0; if (!isCertValid) { logger.error("Signature has been created with expired certificate"); addValidationError(new SignedWithExpiredCertificateException()); } }
From source file:com.thoughtworks.go.security.AuthSSLX509TrustManagerFactory.java
private void logKeyStore(KeyStore store) throws KeyStoreException { Enumeration aliases = store.aliases(); while (aliases.hasMoreElements()) { String alias = (String) aliases.nextElement(); LOG.debug("Trusted certificate '" + alias + "':"); Certificate trustedcert = store.getCertificate(alias); if (trustedcert != null && trustedcert instanceof X509Certificate) { X509Certificate cert = (X509Certificate) trustedcert; 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()); }/*from w w w . ja v a 2 s. c o m*/ } }
From source file:com.archivas.clienttools.arcutils.utils.net.SSLCertChain.java
public Date getValidNotBefore() { X509Certificate cert = getCertificateList().get(0); return cert.getNotBefore(); }
From source file:org.digidoc4j.TSLCertificateSource.java
/** * Add a certificate to the TSL/*from w w w. j a v a2 s .com*/ * <p/> * ServiceTypeIdentifier is http://uri.etsi.org/TrstSvc/Svctype/CA/QC * ServiceStatus is http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/undersupervision * * @param certificate X509 certificate to be added to the list */ public void addTSLCertificate(X509Certificate certificate) { logger.debug(""); ServiceInfo serviceInfo = new ServiceInfo(); serviceInfo.setStatus("http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/undersupervision"); serviceInfo.setType("http://uri.etsi.org/TrstSvc/Svctype/CA/QC"); serviceInfo.setStatusStartDate(certificate.getNotBefore()); addCertificate(certificate, serviceInfo); }