static {
   for (Provider provider : Security.getProviders()) {
     if (provider.getName().startsWith("SunPKCS11")) {
       Security.removeProvider(provider.getName());
     }
   }
 }
  @Override
  public void contextInitialized(ServletContextEvent sce) {
    BouncyCastleProvider bouncyCastleProvider = new BouncyCastleProvider();

    String name = bouncyCastleProvider.getName();
    Security.removeProvider(name);

    Security.addProvider(bouncyCastleProvider);
  }
 /**
  * Stops LDAP server and shuts down the directory service.
  *
  * @param managementClient
  * @param containerId
  * @throws Exception
  * @see
  *     org.jboss.as.arquillian.api.ServerSetupTask#tearDown(org.jboss.as.arquillian.container.ManagementClient,
  *     java.lang.String)
  */
 public void tearDown(ManagementClient managementClient, String containerId) throws Exception {
   ldapServer.stop();
   directoryService.shutdown();
   FileUtils.deleteDirectory(directoryService.getInstanceLayout().getInstanceDirectory());
   if (removeBouncyCastle) {
     try {
       Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
     } catch (SecurityException ex) {
       LOGGER.warn("Cannot deregister BouncyCastleProvider", ex);
     }
   }
 }
Example #4
0
  public static void main(String[] args) throws Exception {

    if (args.length == 5 && args[4].equalsIgnoreCase("BC")) {
      Security.removeProvider("SunPKCS11-NSS");
      Security.removeProvider("SunEC");
      Security.insertProviderAt(new BouncyCastleProvider(), 1);
      System.out.println("Using BC provider");
    }
    for (Provider p : Security.getProviders()) {
      System.out.println(p);
    }
    System.setProperty("java.security.debug", "ssl");
    String path;
    String password;
    String protocol;
    int port;

    if (args.length == 4 || args.length == 5) {
      path = args[0];
      password = args[1];
      protocol = args[2];
      port = Integer.parseInt(args[3]);
    } else if (args.length == 0) {
      path = PATH_TO_JKS;
      password = JKS_PASSWORD;
      protocol = PROTOCOL;
      port = PORT;
    } else {
      System.out.println(
          "Usage (run with): java -jar [name].jar [jks-path] "
              + "[password] [protocol] [port] \n (set [protocol] to TLS)");
      return;
    }

    KeyStore keyStore = readKeyStore(path, password);
    TLSServer server = new TLSServer(keyStore, password, protocol, port);
    Thread t = new Thread(server);
    t.start();
  }
Example #5
0
  /**
   * Called by Spring when application events occur. At the moment we handle: ContextClosedEvent
   * ContextRefreshedEvent RequestHandledEvent
   *
   * <p>This is where we inject the job controllers into the application context, each one under
   * it's own key.
   *
   * @param applicationEvent Spring application event
   */
  public void onApplicationEvent(ApplicationEvent applicationEvent) {
    if (applicationEvent instanceof ContextRefreshedEvent) {
      logger.info("Bootstrap init");

      // Inject the metadata farm to handle all source of metadata
      servletContext.setAttribute(Guanxi.CONTEXT_ATTR_IDP_ENTITY_FARM, entityFarm);
    }

    if (applicationEvent instanceof ContextClosedEvent) {
      if (okToUnloadBCProvider) {
        Provider[] providers = Security.getProviders();

        /* Although addProvider() returns the ID of the newly installed provider,
         * we can't rely on this. If another webapp removes a provider from the list of
         * installed providers, all the other providers shuffle up the list by one, thus
         * invalidating the ID we got from addProvider().
         */
        try {
          for (int i = 0; i < providers.length; i++) {
            if (providers[i].getName().equalsIgnoreCase(Guanxi.BOUNCY_CASTLE_PROVIDER_NAME)) {
              Security.removeProvider(Guanxi.BOUNCY_CASTLE_PROVIDER_NAME);
            }
          }

          // Stop the jobs
          scheduler.shutdown();
        } catch (SecurityException se) {
          /* We'll end up here if a security manager is installed and it refuses us
           * permission to remove the BouncyCastle provider
           */
        } catch (SchedulerException se) {
          logger.error("Could not stop jobs", se);
        }
      }
    }

    if (applicationEvent instanceof RequestHandledEvent) {}
  }
 protected void tearDown() throws Exception {
   super.tearDown();
   Security.removeProvider(support_TestProvider.getName());
 }
 @After
 public void tearDown() {
   // Make sure we remove the provider after one test, so it is not still there affecting the next
   // test
   Security.removeProvider(getProvider());
 }
Example #8
0
 public void close() {
   _mechanisms = null;
   Security.removeProvider(PROVIDER_NAME);
 }
Example #9
0
 public static void disableSpongyCastleOnLollipop() {
   if (Build.VERSION.SDK_INT == 21) {
     Security.removeProvider(spongyCastleProvider.getName());
   }
 }
  /**
   * Inicializa un almac&eacute;n PKCS#11.
   *
   * @param pssCallBack Callback para la recuperaci&oacute;n de la contrase&ntilde;a del
   *     almac&eacute;n.
   * @param params Parametros adicionales para la configuraci&oacute;n del almac&eacute;n.
   * @return Array con los almacenes configurados.
   * @throws AOKeyStoreManagerException Cuando ocurre un error durante la inicializaci&oacute;n.
   * @throws IOException Cuando se indique una contrase&ntilde;a incorrecta para la apertura del
   *     almac&eacute;n.
   * @throws es.gob.afirma.keystores.main.common.MissingSunPKCS11Exception Si no se encuentra la
   *     biblioteca SunPKCS11
   */
  private List<KeyStore> initPKCS11(final PasswordCallback pssCallBack, final Object[] params)
      throws AOKeyStoreManagerException, IOException {
    // En el "params" debemos traer los parametros:
    // [0] -p11lib: Biblioteca PKCS#11, debe estar en el Path (Windows) o en el LD_LIBRARY_PATH
    // (UNIX, Linux, Mac OS X)
    // [1] -desc: Descripcion del token PKCS#11 (opcional)
    // [2] -slot: Numero de lector de tarjeta (Sistema Operativo) [OPCIONAL]

    // Anadimos el proveedor PKCS11 de Sun
    if (params == null || params.length < 2) {
      throw new IOException(
          "No se puede acceder al KeyStore PKCS#11 si no se especifica la biblioteca"); //$NON-NLS-1$
    }
    final String p11lib;
    if (params[0] != null) {
      p11lib = params[0].toString();
    } else {
      throw new IllegalArgumentException(
          "No se puede acceder al KeyStore PKCS#11 si se especifica una biblioteca nula"); //$NON-NLS-1$
    }

    // Numero de lector
    Integer slot = null;
    if (params.length >= 3 && params[2] instanceof Integer) {
      slot = (Integer) params[2];
    }

    // Agregamos un nombre a cada PKCS#11 para asegurarnos de no se
    // agregan mas de una vez como provider.
    // Si ya se cargo el PKCS#11 anteriormente, se volvera a instanciar.
    final String p11ProviderName = new File(p11lib).getName().replace('.', '_').replace(' ', '_');
    Provider p11Provider = Security.getProvider("SunPKCS11-" + p11ProviderName); // $NON-NLS-1$

    if (p11Provider == null) {

      Constructor<?> sunPKCS11Contructor;
      try {
        sunPKCS11Contructor =
            Class.forName("sun.security.pkcs11.SunPKCS11")
                .getConstructor(InputStream.class); // $NON-NLS-1$
      } catch (final Exception e) {
        throw new MissingSunPKCS11Exception(e);
      }

      final byte[] config =
          KeyStoreUtilities.createPKCS11ConfigFile(p11lib, p11ProviderName, slot).getBytes();
      try {
        p11Provider = (Provider) sunPKCS11Contructor.newInstance(new ByteArrayInputStream(config));
      } catch (final Exception e) {
        // El PKCS#11 del DNIe a veces falla a la primera pero va
        // correctamente a la segunda
        // asi que reintentamos una vez mas
        try {
          p11Provider =
              (Provider) sunPKCS11Contructor.newInstance(new ByteArrayInputStream(config));
        } catch (final Exception ex) {
          throw new AOKeyStoreManagerException(
              "No se ha podido instanciar el proveedor SunPKCS11 para la la biblioteca " + p11lib,
              ex); //$NON-NLS-1$
        }
      }
      Security.addProvider(p11Provider);
    } else {
      LOGGER.info(
          "El proveedor SunPKCS11 solicitado ya estaba instanciado, se reutilizara esa instancia: "
              + p11Provider.getName()); // $NON-NLS-1$
    }

    try {
      this.ks = KeyStore.getInstance(this.ksType.getProviderName(), p11Provider);
    } catch (final Exception e) {
      Security.removeProvider(p11Provider.getName());
      p11Provider = null;
      throw new AOKeyStoreManagerException(
          "No se ha podido obtener el almacen PKCS#11", e); // $NON-NLS-1$
    }

    try {
      this.ks.load(null, pssCallBack != null ? pssCallBack.getPassword() : null);
    } catch (final IOException e) {
      if (e.getCause() instanceof UnrecoverableKeyException
          || e.getCause() instanceof BadPaddingException) {
        throw new IOException("Contrasena invalida: " + e, e); // $NON-NLS-1$
      }
      throw new AOKeyStoreManagerException(
          "No se ha podido obtener el almacen PKCS#11 solicitado", e); // $NON-NLS-1$
    } catch (final CertificateException e) {
      Security.removeProvider(p11Provider.getName());
      p11Provider = null;
      throw new AOKeyStoreManagerException(
          "No se han podido cargar los certificados del almacen PKCS#11 solicitado",
          e); //$NON-NLS-1$
    } catch (final NoSuchAlgorithmException e) {
      Security.removeProvider(p11Provider.getName());
      p11Provider = null;
      throw new AOKeyStoreManagerException(
          "No se ha podido verificar la integridad del almacen PKCS#11 solicitado",
          e); //$NON-NLS-1$
    }
    final List<KeyStore> ret = new ArrayList<KeyStore>(1);
    ret.add(this.ks);
    return ret;
  }
Example #11
0
 @Override
 public void stop(BundleContext context) throws Exception {
   Security.removeProvider("BC");
 }
 @AfterClass
 public static void destroy() throws IOException, InterruptedException {
   IoUtils.safeClose(streamServer);
   IoUtils.safeClose(endpoint);
   Security.removeProvider(providerName);
 }