List of usage examples for java.security.cert X509Certificate checkValidity
public abstract void checkValidity() throws CertificateExpiredException, CertificateNotYetValidException;
From source file:net.sf.jsignpdf.utils.KeyStoreUtils.java
/** * Returns list of key aliases in given keystore. * /*from www . j a va2s . c om*/ * @param aKs * @param options * @return */ private static List<String> getAliasesList(final KeyStore aKs, final BasicSignerOptions options) { if (options == null) { throw new NullPointerException("Options are empty."); } if (aKs == null) { throw new NullPointerException(RES.get("error.keystoreNull")); } final List<String> tmpResult = new ArrayList<String>(); try { LOGGER.info(RES.get("console.getAliases")); final Enumeration<String> tmpAliases = aKs.aliases(); final boolean checkValidity = ConfigProvider.getInstance().getAsBool("certificate.checkValidity", true); final boolean checkKeyUsage = ConfigProvider.getInstance().getAsBool("certificate.checkKeyUsage", true); final boolean checkCriticalExtensions = ConfigProvider.getInstance() .getAsBool("certificate.checkCriticalExtensions", true); while (tmpAliases.hasMoreElements()) { String tmpAlias = tmpAliases.nextElement(); if (aKs.isKeyEntry(tmpAlias)) { final Certificate tmpCert = aKs.getCertificate(tmpAlias); boolean tmpAddAlias = true; if (tmpCert instanceof X509Certificate) { final X509Certificate tmpX509 = (X509Certificate) tmpCert; if (checkValidity) { try { tmpX509.checkValidity(); } catch (CertificateExpiredException e) { LOGGER.info(RES.get("console.certificateExpired", tmpAlias)); tmpAddAlias = false; } catch (CertificateNotYetValidException e) { LOGGER.info(RES.get("console.certificateNotYetValid", tmpAlias)); tmpAddAlias = false; } } if (checkKeyUsage) { // check if the certificate is supposed to be // used for digital signatures final boolean keyUsage[] = tmpX509.getKeyUsage(); if (keyUsage != null && keyUsage.length > 0) { // KeyUsage ::= BIT STRING { // digitalSignature (0), // nonRepudiation (1), // keyEncipherment (2), // dataEncipherment (3), // keyAgreement (4), // keyCertSign (5), // cRLSign (6), // encipherOnly (7), // decipherOnly (8) } if (!(keyUsage[0] || keyUsage[1])) { LOGGER.info(RES.get("console.certificateNotForSignature", tmpAlias)); tmpAddAlias = false; } } } // check critical extensions if (checkCriticalExtensions) { final Set<String> criticalExtensionOIDs = tmpX509.getCriticalExtensionOIDs(); if (criticalExtensionOIDs != null) { for (String oid : criticalExtensionOIDs) { if (!Constants.SUPPORTED_CRITICAL_EXTENSION_OIDS.contains(oid)) { LOGGER.info( RES.get("console.criticalExtensionNotSupported", tmpAlias, oid)); tmpAddAlias = false; } } } } } if (tmpAddAlias) { tmpResult.add(tmpAlias); } } } } catch (Exception e) { LOGGER.error(RES.get("console.exception"), e); } return tmpResult; }
From source file:org.dspace.authenticate.X509Authentication.java
/** * Verify CERTIFICATE against KEY. Return true if and only if CERTIFICATE is * valid and can be verified against KEY. * * @param context/*w w w . j a v a 2 s . co m*/ * The current DSpace context * @param certificate - * An X509 certificate object * @return - True if CERTIFICATE is valid and can be verified against KEY, * false otherwise. */ private static boolean isValid(Context context, X509Certificate certificate) { if (certificate == null) { return false; } // This checks that current time is within cert's validity window: try { certificate.checkValidity(); } catch (CertificateException e) { log.info(LogManager.getHeader(context, "authentication", "X.509 Certificate is EXPIRED or PREMATURE: " + e.toString())); return false; } // Try CA public key, if available. if (caPublicKey != null) { try { certificate.verify(caPublicKey); return true; } catch (GeneralSecurityException e) { log.info(LogManager.getHeader(context, "authentication", "X.509 Certificate FAILED SIGNATURE check: " + e.toString())); } } // Try it with keystore, if available. if (caCertKeyStore != null) { try { Enumeration ke = caCertKeyStore.aliases(); while (ke.hasMoreElements()) { String alias = (String) ke.nextElement(); if (caCertKeyStore.isCertificateEntry(alias)) { Certificate ca = caCertKeyStore.getCertificate(alias); try { certificate.verify(ca.getPublicKey()); return true; } catch (CertificateException ce) { } } } log.info(LogManager.getHeader(context, "authentication", "Keystore method FAILED SIGNATURE check on client cert.")); } catch (GeneralSecurityException e) { log.info(LogManager.getHeader(context, "authentication", "X.509 Certificate FAILED SIGNATURE check: " + e.toString())); } } return false; }
From source file:ru.codeinside.gws.crypto.cryptopro.CryptoProvider.java
private static ValidateResult validate(final Element securityToken) throws Exception { final X509Security x509 = new X509Security(securityToken); final X509Certificate cert = (X509Certificate) CertificateFactory.getInstance("X.509") .generateCertificate(new ByteArrayInputStream(x509.getToken())); if (cert == null) { return new ValidateResult("? c ?", null); }// w w w . j a va 2 s.c o m try { cert.checkValidity(); } catch (CertificateException e) { return new ValidateResult(" ? ?", cert); } final Element signature = first(securityToken.getParentNode(), Constants.SignatureSpecNS, "Signature"); if (signature == null) { return new ValidateResult("? ? ?", cert); } final DOMValidateContext ctx = new DOMValidateContext(cert.getPublicKey(), signature); fixWsuId(securityToken.getOwnerDocument(), ctx, new HashSet<String>()); final boolean valid = SIGNATURE_FACTORY.unmarshalXMLSignature(ctx).validate(ctx); return new ValidateResult(valid ? null : "? !", cert); }
From source file:org.cesecore.certificates.ocsp.CanLogCache.java
/** * Checks if a certificate is valid Does also print a WARN if the certificate is about to expire. * //from w ww . jav a2 s. co m * @param signerCert the certificate to be tested * @return true if the certificate is valid */ private static boolean isCertificateValid(X509Certificate signerCert) { try { signerCert.checkValidity(); } catch (CertificateExpiredException e) { log.error(intres.getLocalizedMessage("ocsp.errorcerthasexpired", signerCert.getSerialNumber(), signerCert.getIssuerDN())); return false; } catch (CertificateNotYetValidException e) { log.error(intres.getLocalizedMessage("ocsp.errornotyetvalid", signerCert.getSerialNumber(), signerCert.getIssuerDN())); return false; } final long warnBeforeExpirationTime = OcspConfiguration.getWarningBeforeExpirationTime(); if (warnBeforeExpirationTime < 1) { return true; } final Date warnDate = new Date(new Date().getTime() + warnBeforeExpirationTime); try { signerCert.checkValidity(warnDate); } catch (CertificateExpiredException e) { log.warn(intres.getLocalizedMessage("ocsp.warncertwillexpire", signerCert.getSerialNumber(), signerCert.getIssuerDN(), signerCert.getNotAfter())); } catch (CertificateNotYetValidException e) { throw new Error("This should never happen.", e); } if (!log.isDebugEnabled()) { return true; } log.debug("Time for \"certificate will soon expire\" not yet reached. You will be warned after: " + new Date(signerCert.getNotAfter().getTime() - warnBeforeExpirationTime)); return true; }
From source file:ru.elifantiev.yandex.YandexSSLSocketFactory.java
YandexSSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { super(truststore); TrustManager tm = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] x509Certificates, String authType) throws CertificateException { }//from w w w . j a v a 2 s . c o m public void checkServerTrusted(X509Certificate[] certificates, String authType) throws CertificateException { for (X509Certificate cert : certificates) cert.checkValidity(); } public X509Certificate[] getAcceptedIssuers() { return null; } }; sslContext.init(null, new TrustManager[] { tm }, null); }
From source file:mx.bigdata.cfdi.CFDv3Debugger.java
public void dumpDigests() throws Exception { System.err.println(cfd.getOriginalString()); byte[] digest = cfd.getDigest(); CFDv3.dump("Digestion generada", digest, System.err); String certStr = cfd.document.getCertificado(); Base64 b64 = new Base64(); byte[] cbs = b64.decode(certStr); X509Certificate cert = KeyLoader.loadX509Certificate(new ByteArrayInputStream(cbs)); cert.checkValidity(); String sigStr = cfd.document.getSello(); byte[] signature = b64.decode(sigStr); CFDv3.dump("Digestion firmada", signature, System.err); Cipher dec = Cipher.getInstance("RSA"); dec.init(Cipher.DECRYPT_MODE, cert); byte[] result = dec.doFinal(signature); CFDv3.dump("Digestion decriptada", result, System.err); ASN1InputStream aIn = new ASN1InputStream(result); ASN1Sequence seq = (ASN1Sequence) aIn.readObject(); ASN1OctetString sigHash = (ASN1OctetString) seq.getObjectAt(1); CFDv3.dump("Sello", sigHash.getOctets(), System.err); }
From source file:com.eucalyptus.www.X509Download.java
private static byte[] getX509Zip(User u) throws Exception { X509Certificate cloudCert = null; final X509Certificate x509; String userAccessKey = null;// w w w . j a v a 2 s . co m String userSecretKey = null; KeyPair keyPair = null; try { for (AccessKey k : u.getKeys()) { if (k.isActive()) { userAccessKey = k.getAccessKey(); userSecretKey = k.getSecretKey(); } } if (userAccessKey == null) { AccessKey k = u.createKey(); userAccessKey = k.getAccessKey(); userSecretKey = k.getSecretKey(); } keyPair = Certs.generateKeyPair(); x509 = Certs.generateCertificate(keyPair, u.getName()); x509.checkValidity(); u.addCertificate(x509); cloudCert = SystemCredentials.lookup(Eucalyptus.class).getCertificate(); } catch (Exception e) { LOG.fatal(e, e); throw e; } ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); ZipArchiveOutputStream zipOut = new ZipArchiveOutputStream(byteOut); ZipArchiveEntry entry = null; String fingerPrint = Certs.getFingerPrint(keyPair.getPublic()); if (fingerPrint != null) { String baseName = X509Download.NAME_SHORT + "-" + u.getName() + "-" + fingerPrint.replaceAll(":", "").toLowerCase().substring(0, 8); zipOut.setComment("To setup the environment run: source /path/to/eucarc"); StringBuilder sb = new StringBuilder(); //TODO:GRZE:FIXME velocity String userNumber = u.getAccount().getAccountNumber(); sb.append("EUCA_KEY_DIR=$(cd $(dirname ${BASH_SOURCE:-$0}); pwd -P)"); final Optional<String> computeUrl = remotePublicify(Compute.class); if (computeUrl.isPresent()) { sb.append(entryFor("EC2_URL", null, computeUrl)); } else { sb.append("\necho WARN: Eucalyptus URL is not configured. >&2"); ServiceBuilder<? extends ServiceConfiguration> builder = ServiceBuilders.lookup(Compute.class); ServiceConfiguration localConfig = builder.newInstance(Internets.localHostAddress(), Internets.localHostAddress(), Internets.localHostAddress(), Eucalyptus.INSTANCE.getPort()); sb.append("\nexport EC2_URL=" + ServiceUris.remotePublicify(localConfig)); } sb.append(entryFor("S3_URL", "An OSG is either not registered or not configured. S3_URL is not set. " + "Please register an OSG and/or set a valid s3 endpoint and download credentials again. " + "Or set S3_URL manually to http://OSG-IP:8773/services/objectstorage", remotePublicify(ObjectStorage.class))); sb.append(entryFor("EUARE_URL", "EUARE URL is not configured.", remotePublicify(Euare.class))); sb.append(entryFor("TOKEN_URL", "TOKEN URL is not configured.", remotePublicify(Tokens.class))); sb.append(entryFor("AWS_AUTO_SCALING_URL", "Auto Scaling service URL is not configured.", remotePublicify(AutoScaling.class))); sb.append(entryFor("AWS_CLOUDFORMATION_URL", null, remotePublicify(CloudFormation.class))); sb.append(entryFor("AWS_CLOUDWATCH_URL", "Cloud Watch service URL is not configured.", remotePublicify(CloudWatch.class))); sb.append(entryFor("AWS_ELB_URL", "Load Balancing service URL is not configured.", remotePublicify(LoadBalancing.class))); sb.append("\nexport EUSTORE_URL=" + StackConfiguration.DEFAULT_EUSTORE_URL); sb.append("\nexport EC2_PRIVATE_KEY=${EUCA_KEY_DIR}/" + baseName + "-pk.pem"); sb.append("\nexport EC2_CERT=${EUCA_KEY_DIR}/" + baseName + "-cert.pem"); sb.append("\nexport EC2_JVM_ARGS=-Djavax.net.ssl.trustStore=${EUCA_KEY_DIR}/jssecacerts"); sb.append("\nexport EUCALYPTUS_CERT=${EUCA_KEY_DIR}/cloud-cert.pem"); sb.append("\nexport EC2_ACCOUNT_NUMBER='" + u.getAccount().getAccountNumber() + "'"); sb.append("\nexport EC2_ACCESS_KEY='" + userAccessKey + "'"); sb.append("\nexport EC2_SECRET_KEY='" + userSecretKey + "'"); sb.append("\nexport AWS_ACCESS_KEY='" + userAccessKey + "'"); sb.append("\nexport AWS_SECRET_KEY='" + userSecretKey + "'"); sb.append("\nexport AWS_CREDENTIAL_FILE=${EUCA_KEY_DIR}/iamrc"); sb.append("\nexport EC2_USER_ID='" + userNumber + "'"); sb.append( "\nalias ec2-bundle-image=\"ec2-bundle-image --cert ${EC2_CERT} --privatekey ${EC2_PRIVATE_KEY} --user ${EC2_ACCOUNT_NUMBER} --ec2cert ${EUCALYPTUS_CERT}\""); sb.append( "\nalias ec2-upload-bundle=\"ec2-upload-bundle -a ${EC2_ACCESS_KEY} -s ${EC2_SECRET_KEY} --url ${S3_URL}\""); sb.append("\n"); zipOut.putArchiveEntry(entry = new ZipArchiveEntry("eucarc")); entry.setUnixMode(0600); zipOut.write(sb.toString().getBytes("UTF-8")); zipOut.closeArchiveEntry(); sb = new StringBuilder(); sb.append("AWSAccessKeyId=").append(userAccessKey).append('\n'); sb.append("AWSSecretKey=").append(userSecretKey); zipOut.putArchiveEntry(entry = new ZipArchiveEntry("iamrc")); entry.setUnixMode(0600); zipOut.write(sb.toString().getBytes("UTF-8")); zipOut.closeArchiveEntry(); /** write the private key to the zip stream **/ zipOut.putArchiveEntry(entry = new ZipArchiveEntry("cloud-cert.pem")); entry.setUnixMode(0600); zipOut.write(PEMFiles.getBytes(cloudCert)); zipOut.closeArchiveEntry(); zipOut.putArchiveEntry(entry = new ZipArchiveEntry("jssecacerts")); entry.setUnixMode(0600); KeyStore tempKs = KeyStore.getInstance("jks"); tempKs.load(null); tempKs.setCertificateEntry("eucalyptus", cloudCert); ByteArrayOutputStream bos = new ByteArrayOutputStream(); tempKs.store(bos, "changeit".toCharArray()); zipOut.write(bos.toByteArray()); zipOut.closeArchiveEntry(); /** write the private key to the zip stream **/ zipOut.putArchiveEntry(entry = new ZipArchiveEntry(baseName + "-pk.pem")); entry.setUnixMode(0600); zipOut.write(PEMFiles.getBytes("RSA PRIVATE KEY", Crypto.getCertificateProvider().getEncoded(keyPair.getPrivate()))); zipOut.closeArchiveEntry(); /** write the X509 certificate to the zip stream **/ zipOut.putArchiveEntry(entry = new ZipArchiveEntry(baseName + "-cert.pem")); entry.setUnixMode(0600); zipOut.write(PEMFiles.getBytes(x509)); zipOut.closeArchiveEntry(); } /** close the zip output stream and return the bytes **/ zipOut.close(); return byteOut.toByteArray(); }
From source file:EasyX509TrustManager.java
/** * @see com.sun.net.ssl.X509TrustManager#isServerTrusted(X509Certificate[]) *//* w w w.j ava 2 s. c o m*/ public boolean isServerTrusted(X509Certificate[] certificates) { if ((certificates != null) && LOG.isDebugEnabled()) { LOG.debug("Server certificate chain:"); for (int i = 0; i < certificates.length; i++) { LOG.debug("X509Certificate[" + i + "]=" + certificates[i]); } } if ((certificates != null) && (certificates.length == 1)) { X509Certificate certificate = certificates[0]; try { certificate.checkValidity(); } catch (CertificateException e) { LOG.error(e.toString()); return false; } return true; } else { return this.standardTrustManager.isServerTrusted(certificates); } }
From source file:mx.bigdata.sat.cfdi.CFDv3Debugger.java
private void dumpDigests() throws Exception { System.err.println(cfd.getCadenaOriginal()); String certStr = cfd.document.getCertificado(); Base64 b64 = new Base64(); byte[] cbs = b64.decode(certStr); X509Certificate cert = (X509Certificate) KeyLoaderFactory .createInstance(KeyLoaderEnumeration.PUBLIC_KEY_LOADER, new ByteArrayInputStream(cbs)).getKey(); cert.checkValidity(); String sigStr = cfd.document.getSello(); byte[] signature = b64.decode(sigStr); CFDv3.dump("Digestion firmada", signature, System.err); Cipher dec = Cipher.getInstance("RSA"); dec.init(Cipher.DECRYPT_MODE, cert); byte[] result = dec.doFinal(signature); CFDv3.dump("Digestion decriptada", result, System.err); ASN1InputStream aIn = new ASN1InputStream(result); ASN1Sequence seq = (ASN1Sequence) aIn.readObject(); ASN1OctetString sigHash = (ASN1OctetString) seq.getObjectAt(1); CFDv3.dump("Sello", sigHash.getOctets(), System.err); }