List of usage examples for org.bouncycastle.jce.provider BouncyCastleProvider PROVIDER_NAME
String PROVIDER_NAME
To view the source code for org.bouncycastle.jce.provider BouncyCastleProvider PROVIDER_NAME.
Click Source Link
From source file:org.sonatype.nexus.crypto.internal.MavenCipherImplTest.java
License:Open Source License
@After public void cleanup() { Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME); }
From source file:org.sonatype.nexus.plugins.bcprov.internal.BCPluginEventHandler.java
License:Open Source License
/** * {@link NexusStoppedEvent} handler: unregister BC provider if needed (if it was registered by us, not by some 3rd party). * // ww w . j ava 2s.c o m * @param e the event (not used) */ @Subscribe public void onNexusStoppedEvent(final NexusStoppedEvent e) { if (registered) { Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME); logger.debug("BouncyCastle security provider unregistered"); } }
From source file:org.sonatype.nexus.ssl.CertificateUtilTest.java
License:Open Source License
@Before public void registerBouncyCastle() { if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { Security.addProvider(new BouncyCastleProvider()); }/*from ww w. j a v a 2s . c o m*/ }
From source file:org.sufficientlysecure.keychain.KeychainApplication.java
License:Open Source License
/** * Called when the application is starting, before any activity, service, or receiver objects * (excluding content providers) have been created. *//*from ww w.j ava2s. c o m*/ @Override public void onCreate() { super.onCreate(); /* * Sets our own Bouncy Castle library as preferred security provider * * because Android's default provider config has BC at position 3, * we need to remove it and insert BC again at position 1 (above OpenSSLProvider!) * * (insertProviderAt() position starts from 1) */ Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME); Security.insertProviderAt(new BouncyCastleProvider(), 1); /* * apply RNG fixes * * among other things, executes Security.insertProviderAt(new * LinuxPRNGSecureRandomProvider(), 1) for Android <= SDK 17 */ PRNGFixes.apply(); Log.d(Constants.TAG, "Bouncy Castle set and PRNG Fixes applied!"); /* if (Constants.DEBUG) { Provider[] providers = Security.getProviders(); Log.d(Constants.TAG, "Installed Security Providers:"); for (Provider p : providers) { Log.d(Constants.TAG, "provider class: " + p.getClass().getName()); } } */ // Create OpenKeychain directory on sdcard if not existing if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { if (!Constants.Path.APP_DIR.exists() && !Constants.Path.APP_DIR.mkdirs()) { // ignore this for now, it's not crucial // that the directory doesn't exist at this point } } brandGlowEffect(getApplicationContext(), FormattingUtils.getColorFromAttr(getApplicationContext(), R.attr.colorPrimary)); // Add OpenKeychain account to Android to link contacts with keys and keyserver sync createAccountIfNecessary(this); if (Preferences.getKeyserverSyncEnabled(this)) { // will update a keyserver sync if the interval has changed KeyserverSyncAdapterService.enableKeyserverSync(this); } // if first time, enable keyserver and contact sync if (Preferences.getPreferences(this).isFirstTime()) { KeyserverSyncAdapterService.enableKeyserverSync(this); ContactSyncAdapterService.enableContactsSync(this); } // Update keyserver list as needed Preferences.getPreferences(this).upgradePreferences(this); TlsHelper.addPinnedCertificate("hkps.pool.sks-keyservers.net", getAssets(), "hkps.pool.sks-keyservers.net.CA.cer"); TlsHelper.addPinnedCertificate("pgp.mit.edu", getAssets(), "pgp.mit.edu.cer"); TlsHelper.addPinnedCertificate("api.keybase.io", getAssets(), "api.keybase.io.CA.cer"); TemporaryFileProvider.cleanUp(this); if (!checkConsolidateRecovery()) { // force DB upgrade, https://github.com/open-keychain/open-keychain/issues/1334 new KeychainDatabase(this).getReadableDatabase().close(); } }
From source file:org.viafirma.nucleo.validacion.CRLUtil.java
License:Open Source License
/** * Retorna el listado de CRLs para los certificados que tienen informacin * correcta sobre sus puntos de distrubicin. 1.- Recupera las urls de los * puntos de distribucin de crls. 2.- Se descarga todas las crls. * //from w ww . ja va 2 s. c o m * @param certificadoX509 * @return * @throws NoSuchProviderException * @throws CertificateException */ private List<X509CRL> getCrlsPuntoDistribucion(X509Certificate certificadoX509) throws CertificateException, NoSuchProviderException { CertificateFactory factoriaCertificados = CertificateFactory.getInstance("X.509", BouncyCastleProvider.PROVIDER_NAME); List<String> urls = null; // recuperos los puntos de distribucin definidos del certificado. urls = getCrlPuntosDeDistribucion(certificadoX509); List<X509CRL> crls = new LinkedList<X509CRL>(); if (urls != null) { // itero sobre las urls para ir obteniendo los listados for (String hostURL : urls) { log.debug("url ->" + hostURL); try { if (hostURL == null) { log.debug("La url de la crl no es correcta."); } else if (!hostURL.startsWith("http:")) { log.debug("La url de la crl no es correcta. " + hostURL); } else { InputStream ioCrl = getIoCrlFromUrl(hostURL); // leo el io para generar un fichero de crl X509CRL crl = (X509CRL) factoriaCertificados.generateCRL(ioCrl); if (crl != null) { crls.add(crl); // log.debug("CRLer -->" + crl.get()); log.debug("Effective From -->" + crl.getThisUpdate()); log.debug("Nextate -->" + crl.getNextUpdate()); } else { log.debug("No se puede recuperar o no es un cert valido " + hostURL); } try { ioCrl.close(); } catch (Exception e) { // No se ha podido cerrar la conexin con la crl, sin importancia. } // no importa si no podemos cerrar la conexin( // significa que ya esta cerrada) } } catch (CRLException e) { log.warn( "no se ha podido conectar a host para descargar las crls, en este momento no estan disponibles." + e.getMessage(), e); // e.printStackTrace(); } catch (Exception e) { log.warn( "no se ha podido conectar a host para descargar las crls, en este momento no estan disponibles." + e.getMessage(), e); e.printStackTrace(); } } } return crls; }
From source file:org.viafirma.nucleo.validacion.CRLUtil.java
License:Open Source License
/** * Recupera el listado de Crls obtenidas desde el LDAP. * TODO: Separar cada implementacin en un IMPL concreto que tenga que cumplir con una interfaz * para resolver las crls y para parsear el certificado * NOTA: para utilizar de forma oficial la validazin de CRLs de la FNMT es necesario firmar un convenio. * /*from w ww . j a va2 s . c o m*/ * @param certificadoX509 * @return */ private List<X509CRL> getCrlLDAPFNMT(X509Certificate certificadoX509) { List<X509CRL> crls = new LinkedList<X509CRL>(); // ******************************************************************************** // si es un certiticado de la FNMT hay que acceder al ldap para // recuperar las crls. try { CertificateFactory factoriaCertificados = CertificateFactory.getInstance("X.509", BouncyCastleProvider.PROVIDER_NAME); // es un certificado de la FNMT. el procesamiento es diferente // al resto, es atacando a un LDAP // recuperamos del LDAP el certificado // NOTA: Esta url es solo para pruebas, para utilizar de forma // oficial la validazin de CRLs de la FNMT es necesario firmar un // convenio // ldap-2.cert.fnmt.es:389 InputStream ioCrl = getIoCrlFromFNMTLDAP(certificadoX509); if (ioCrl != null) { // la crl del fichero actual esta publicada, recuperamos la crl // leo el io para generar un fichero de crl System.out.println("***ioCrl:" + ioCrl); X509CRL crl = (X509CRL) factoriaCertificados.generateCRL(ioCrl); System.out.println("***Despues deioCrl:" + crl); try { if (crl != null) { crls.add(crl); System.out.println("***3:" + crl.getIssuerDN()); log.debug("CRLer -->" + crl.getIssuerDN()); log.debug("Effective From -->" + crl.getThisUpdate()); log.debug("Nextate -->" + crl.getNextUpdate()); crls.add(crl); } else { log.debug("No se puede recuperar o no es un cert valido ."); } ioCrl.close(); } catch (Throwable e) { log.warn("Problemas al recuperar la crl ." + e.getMessage()); e.printStackTrace(); } // no importa si no podemos cerrar la conexin( significa // que ya esta cerrada) } else { log.error("No se ha recuperado la crl."); } } catch (CRLException e) { log.warn("No se puede recuperar la crl." + e.getMessage()); } catch (Throwable e) { e.printStackTrace(); } return crls; }
From source file:org.viafirma.nucleo.validacion.CRLValidationHandler.java
License:Apache License
/** * Metodo encargado de la verificacin de los certificados * /*from w ww. j av a2 s . c om*/ * @param certificadoX509 * @throws ExcepcionErrorInterno */ public CodigoError validarCRL(X509Certificate certificadoX509) { try { // 1.- Inicia la factoria de certificados CertificateFactory factoriaCertificados = CertificateFactory.getInstance("X.509", BouncyCastleProvider.PROVIDER_NAME); log.debug("Validando certificado perteneciente a: " + certificadoX509.getIssuerDN()); CertPathValidator validador = CertPathValidator.getInstance("PKIX", BouncyCastleProvider.PROVIDER_NAME); // 2.- Configuracin de los parametros del validador // 2.1.- Para comprobar que el camino de confianza no esta roto, // tengo en cuenta todos los certificados PKIXParameters parametros = new PKIXParameters(certificadosConfianza); // Fecha para la comprobacin de validez. parametros.setDate(new Date()); if (validacionOnline) { // Para la validacin online de del estado de revocacin de los // certificados // ************ // creo un almacen( cache ) de certificados y CRLs para no tener // que conectarme a las crls // en cada validacin // Genero un listado de las CRLS que vamos a utilizar para la // validacin del certificado. List<CRL> listaCRLsCertificadosAlmacenados = new LinkedList<CRL>(); // Aade las crls de los certificados de confianza reconocidos // por Viafirma. // estos certificados son los marcados con el prefijo viafirma_ for (TrustAnchor trustAnchor : certificadosConfianza) { // TODO establecer un sistema de cache eficiente // TODO recuperar solo las crls del certificado en uso. listaCRLsCertificadosAlmacenados .addAll(CRLUtil.getCurrentInstance().getCRLs(trustAnchor.getTrustedCert())); // para cada certificado. } // aado al listado todas las crls del certificado actual. EJ // para el caso de // un certificado de FNMT el certificado personal contiene CN = // CRL1827,OU = FNMT Clase 2 CA,O = FNMT,C = ES listaCRLsCertificadosAlmacenados.addAll(CRLUtil.getCurrentInstance().getCRLs(certificadoX509)); // parametros para la creacin del almacen(cache CRLs) CollectionCertStoreParameters params = new CollectionCertStoreParameters( listaCRLsCertificadosAlmacenados); CertStore almacen = CertStore.getInstance("Collection", params, BouncyCastleProvider.PROVIDER_NAME); parametros.addCertStore(almacen); } else { // No se utilizan las CRLs para la comprobacin de la // revocacin. parametros.setRevocationEnabled(false); } // certificados a validar ( solo 1) List<X509Certificate> certificadosValidar = new ArrayList<X509Certificate>(1); certificadosValidar.add(certificadoX509); // genero el listado de certificados a validar CertPath certPath = factoriaCertificados.generateCertPath(certificadosValidar); // validacin CertPathValidatorResult resultado = validador.validate(certPath, parametros); if (log.isDebugEnabled()) { if (resultado instanceof java.security.cert.PKIXCertPathValidatorResult) { // pintamos el arbol de politicas PolicyNode node = ((java.security.cert.PKIXCertPathValidatorResult) resultado).getPolicyTree(); StringBuffer ruta = new StringBuffer( "Certificado vlido: " + certificadoX509.getSubjectDN().getName()); while (node != null) { ruta.append("-->"); ruta.append(node.getValidPolicy()); if (node.getChildren().hasNext()) { node = node.getChildren().next(); } else { node = null; } } log.info("ruta de validacin: " + ruta); } } return CodigoError.OK_CERTIFICADO_VALIDADO; } catch (CertificateException e) { log.fatal(CodigoError.ERROR_INTERNO, e); return CodigoError.ERROR_INTERNO; } catch (NoSuchProviderException e) { log.fatal(CodigoError.ERROR_INTERNO, e); return CodigoError.ERROR_INTERNO; } catch (NoSuchAlgorithmException e) { log.fatal(CodigoError.ERROR_INTERNO, e); return CodigoError.ERROR_INTERNO; } catch (InvalidAlgorithmParameterException e) { log.fatal(CodigoError.ERROR_VALIDACION_CONFIGURACION_PARAMETRO, e); return CodigoError.ERROR_VALIDACION_CONFIGURACION_PARAMETRO; } catch (CRLException e) { log.fatal(CodigoError.ERROR_VALIDACION_CRL, e); return CodigoError.ERROR_VALIDACION_CRL; } catch (CertPathValidatorException e) { // detectamos el tipo de problema if (e.getMessage().contains(java.security.cert.CertificateExpiredException.class.getName()) || e.getMessage().contains("Certificate revocation after") || e.getMessage().contains("NotAfter") || e.getMessage().contains("certificate expired on")) { log.warn("El certificado esta caducado." + e.getMessage() + " " + certificadoX509.getSubjectDN()); return CodigoError.ERROR_VALIDACION_CERTIFICADO_CADUCADO; } else if (e.getMessage().contains(java.security.SignatureException.class.getName())) { log.warn( "Algunos de los certificados en el camino de certificacin no tiene crl. Algunos de los certificados no se puede validar." + e.getMessage() + " " + certificadoX509.getSubjectDN()); return CodigoError.ERROR_VALIDACION_CRL; } else if (e.getMessage().contains("no valid CRL found")) { log.warn("No se ha podido comprobar la validez del certificado. " + e.getMessage() + " " + certificadoX509.getSubjectDN()); return CodigoError.ERROR_VALIDACION_CRL; } else if (e.getMessage().contains("CertPath not found")) { log.warn("Autoridad de certificacin no reconicida." + e.getMessage() + " " + certificadoX509.getIssuerDN()); return CodigoError.ERROR_VALIDACION_AUTORIDAD_NO_RECONOCIDA; } else { log.warn("Autoridad de certificacin no reconicida." + e.getMessage() + " " + certificadoX509.getIssuerDN()); return CodigoError.ERROR_VALIDACION_AUTORIDAD_NO_RECONOCIDA; } // TODO java.security.cert.CertPathValidatorException: couldn't // validate certificate: // java.security.cert.CertificateNotYetValidException: NotBefore: // Thu Apr 19 19:22:17 CEST 2007 // at // org.bouncycastle.jce.provider.PKIXCertPathValidatorSpi.engineValidate(PKIXCertPathValidatorSpi.java:819) } }
From source file:org.viafirma.nucleo.validacion.OcspValidatorHandler.java
License:Apache License
/** * Comprueba que la respuesta OCSP no ha sido manipulada y es correcta. * /*from w w w . j a va 2 s. c o m*/ * @param certificadoX509Emisor * @param brep * @throws OCSPException * @throws CertPathValidatorException */ private void checkOCSP(BasicOCSPResp ocspResponse) throws OCSPException, CertPathValidatorException { // Recuperamos la clave pblica esperada con el OCSP firmo la respuesta. X509Certificate certificatePath[] = null; try { certificatePath = ocspResponse.getCerts(BouncyCastleProvider.PROVIDER_NAME); } catch (NoSuchProviderException e) { throw new CertPathValidatorException("La respuesta OCSP no puede ser validada.", e); } // Recuperamos el inicio del camino ( suponemos que el resto de // certificados estara ya if (certificatePath == null || certificatePath.length == 0) { throw new CertPathValidatorException( "No se ha podido encontrar un certificado en la respuesta OCSP. La respuesta OCSP debe ser firmada por el servidor de OCSP."); } X509Certificate certificadoResponseOCSP = certificatePath[0]; // Recuperamos la clave pblica almacenada en nuestros certificados de // confianza. PublicKey keyCertificadoOCSP = getPublicKeyBySubjectName(certificadoResponseOCSP); if (keyCertificadoOCSP == null) { throw new CertPathValidatorException( "No hay un certificado de confianza asociado a al certificado con el que se firmo esta respuesta OCSP. " + certificadoResponseOCSP.getSubjectDN().getName()); } try { if (!ocspResponse.verify(keyCertificadoOCSP, BouncyCastleProvider.PROVIDER_NAME)) { throw new CertPathValidatorException( "La respuesta OCSP no es vlida, La firma no corresponde a un certificado de confianza."); } } catch (NoSuchProviderException e) { throw new CertPathValidatorException("La respuesta OCSP no puede ser validada.", e); } }
From source file:org.viafirma.util.SendMailUtil.java
License:Open Source License
public MultiPartEmail buildMessage(String subject, String mailTo, String texto, String htmlTexto, String alias, String password) throws ExcepcionErrorInterno, ExcepcionCertificadoNoEncontrado { try {/*from www .jav a2 s. c om*/ // 1.- Preparamos el certificado // Recuperamos la clave privada asociada al alias PrivateKey privateKey = KeyStoreLoader.getPrivateKey(alias, password); if (privateKey == null) { throw new ExcepcionCertificadoNoEncontrado( "No existe una clave privada para el alias '" + alias + "'"); } if (log.isDebugEnabled()) log.info("Firmando el documento con el certificado " + alias); // Recuperamos el camino de confianza asociado al certificado List<Certificate> chain = KeyStoreLoader.getCertificateChain(alias); // Obtenemos los datos del certificado utilizado. X509Certificate certificadoX509 = (X509Certificate) chain.get(0); CertificadoGenerico datosCertificado = CertificadoGenericoFactory.getInstance() .generar(certificadoX509); String emailFrom = datosCertificado.getEmail(); String emailFromDesc = datosCertificado.getCn(); if (StringUtils.isEmpty(emailFrom)) { log.warn("El certificado indicado no tiene un email asociado, No es vlido para firmar emails" + datosCertificado); throw new ExcepcionCertificadoNoEncontrado( "El certificado indicado no tiene un email asociado, No es vlido para firmar emails."); } CertStore certificadosYcrls = CertStore.getInstance("Collection", new CollectionCertStoreParameters(chain), BouncyCastleProvider.PROVIDER_NAME); // 2.- Preparamos el mail MimeBodyPart bodyPart = new MimeBodyPart(); MimeMultipart dataMultiPart = new MimeMultipart(); MimeBodyPart msgHtml = new MimeBodyPart(); if (StringUtils.isNotEmpty(htmlTexto)) { msgHtml.setContent(htmlTexto, Email.TEXT_HTML + "; charset=UTF-8"); } else { msgHtml.setContent("<p>" + htmlTexto + "</p>", Email.TEXT_PLAIN + "; charset=UTF-8"); } // create the message we want signed MimeBodyPart mensajeTexto = new MimeBodyPart(); if (StringUtils.isNotEmpty(texto)) { mensajeTexto.setText(texto, "UTF-8"); } else if (StringUtils.isEmpty(texto)) { mensajeTexto.setText(CadenaUtilities.cleanHtml(htmlTexto), "UTF-8"); } dataMultiPart.addBodyPart(mensajeTexto); dataMultiPart.addBodyPart(msgHtml); bodyPart.setContent(dataMultiPart); // Crea el nuevo mensaje firmado MimeMultipart multiPart = createMultipartWithSignature(privateKey, certificadoX509, certificadosYcrls, bodyPart); // Creamos el mensaje que finalmente sera enviadio. MultiPartEmail mail = createMultiPartEmail(subject, mailTo, emailFrom, emailFromDesc, multiPart, multiPart.getContentType()); return mail; } catch (InvalidAlgorithmParameterException e) { throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e); } catch (NoSuchAlgorithmException e) { throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e); } catch (NoSuchProviderException e) { throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e); } catch (MessagingException e) { throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e); } catch (CertificateParsingException e) { throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e); } catch (CertStoreException e) { throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e); } catch (SMIMEException e) { throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e); } catch (EmailException e) { throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e); } }
From source file:org.viafirma.util.SendMailUtil.java
License:Open Source License
/** * Crea un nuevo mail firmado. Adjuntandole el pkcs7. * /*from ww w .j a v a 2s .co m*/ * @param key * Clave privada con la que se realiza el proceso de firma. * @param cert * Certificado utilizado. * @param certsAndCRLs * Camino de confianza. * @param dataPart * Cuerpo del email. * @return Mail firmado. * @throws CertStoreException * @throws SMIMEException * @throws NoSuchAlgorithmException * @throws NoSuchProviderException * @throws CertificateParsingException */ private MimeMultipart createMultipartWithSignature(PrivateKey key, X509Certificate cert, CertStore certsAndCRLs, MimeBodyPart dataPart) throws CertStoreException, SMIMEException, NoSuchAlgorithmException, NoSuchProviderException, CertificateParsingException { // Aadimos los tipos soportados ASN1EncodableVector signedAttrs = new ASN1EncodableVector(); SMIMECapabilityVector caps = new SMIMECapabilityVector(); caps.addCapability(SMIMECapability.aES256_CBC); caps.addCapability(SMIMECapability.dES_EDE3_CBC); caps.addCapability(SMIMECapability.rC2_CBC, 128); signedAttrs.add(new SMIMECapabilitiesAttribute(caps)); signedAttrs.add(new SMIMEEncryptionKeyPreferenceAttribute(SMIMEUtil.createIssuerAndSerialNumberFor(cert))); // Creamos el generador SMIMESignedGenerator generador = new SMIMESignedGenerator(); // Establecemos la clave privada y el mtodo de firma generador.addSigner(key, cert, SMIMESignedGenerator.DIGEST_SHA1, new AttributeTable(signedAttrs), null); // Aadimos el camino de confianza adjuntado en el mail. generador.addCertificatesAndCRLs(certsAndCRLs); // Generamos el mail firmado. MimeMultipart mensajeFirmado = generador.generate(dataPart, BouncyCastleProvider.PROVIDER_NAME); // multipart/mixed; boundary="----=_Part_2_29796765.1208556677256" try { String contentType = mensajeFirmado.getBodyPart(0).getContentType(); contentType = contentType.replaceAll("multipart/mixed", "multipart/alternative"); mensajeFirmado.getBodyPart(0).setHeader("Content-Type", contentType); // contentType =mensajeFirmado.getContentType(); // contentType=contentType.replaceAll("application/pkcs7-signature", // "application/x-pkcs7-signature"); // mensajeFirmado.getContentType(); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return mensajeFirmado; }