Java Code Examples for java.security.Security#getProviders()

The following examples show how to use java.security.Security#getProviders() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestKeyStoreEntry.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
public void run() throws Exception {

        Provider[] providers = Security.getProviders();
        for (Provider p: providers) {
            String prvName = p.getName();
            if (prvName.startsWith("SunJCE")
                    || prvName.startsWith("SunPKCS11-Solaris")) {
                try {
                    runTest(p);
                    out.println("Test with provider " + p.getName() + ""
                            + " passed");

                } catch (java.security.KeyStoreException e) {
                    if (prvName.startsWith("SunPKCS11-Solaris")) {
                        out.println("KeyStoreException is expected because "
                                + "PKCS11KeyStore is invalid keystore type.");
                        e.printStackTrace();
                    } else {
                        throw e;
                    }
                }
            }
        }
    }
 
Example 2
Source File: ProviderVersionCheck.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String arg[]) throws Exception{

        boolean failure = false;

        for (Provider p: Security.getProviders()) {
            System.out.print(p.getName() + " ");
            if (p.getVersion() != 1.8d) {
                System.out.println("failed. " + "Version received was " +
                        p.getVersion());
                failure = true;
            } else {
                System.out.println("passed.");
            }
        }

        if (failure) {
            throw new Exception("Provider(s) failed to have the expected " +
                    "version value.");
        }
    }
 
Example 3
Source File: ZygoteInit.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Register AndroidKeyStoreProvider and warm up the providers that are already registered.
 *
 * By doing it here we avoid that each app does it when requesting a service from the
 * provider for the first time.
 */
private static void warmUpJcaProviders() {
    long startTime = SystemClock.uptimeMillis();
    Trace.traceBegin(
            Trace.TRACE_TAG_DALVIK, "Starting installation of AndroidKeyStoreProvider");
    // AndroidKeyStoreProvider.install() manipulates the list of JCA providers to insert
    // preferred providers. Note this is not done via security.properties as the JCA providers
    // are not on the classpath in the case of, for example, raw dalvikvm runtimes.
    AndroidKeyStoreProvider.install();
    Log.i(TAG, "Installed AndroidKeyStoreProvider in "
            + (SystemClock.uptimeMillis() - startTime) + "ms.");
    Trace.traceEnd(Trace.TRACE_TAG_DALVIK);

    startTime = SystemClock.uptimeMillis();
    Trace.traceBegin(
            Trace.TRACE_TAG_DALVIK, "Starting warm up of JCA providers");
    for (Provider p : Security.getProviders()) {
        p.warmUpServiceProvision();
    }
    Log.i(TAG, "Warmed up JCA providers in "
            + (SystemClock.uptimeMillis() - startTime) + "ms.");
    Trace.traceEnd(Trace.TRACE_TAG_DALVIK);
}
 
Example 4
Source File: Sign.java    From ClientSPV with MIT License 6 votes vote down vote up
public void releaseToken() {
    try {
        for (Provider p : Security.getProviders()) {
            if (p.getName().contains("SunPKCS11")) {
                Security.removeProvider(p.getName());
            }
        }
        if (_p11Class != null && _p11 != null) {
            Method mth = _p11Class.getMethod("finalize", null);
            mth.invoke(_p11);
        }
        _p11Class = null;
        _p11 = null;
        Thread.sleep(1000);
    } catch (Throwable ex) {
        logger.error("err17: ", ex);
    }
}
 
Example 5
Source File: ProviderVersionCheck.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String arg[]) throws Exception{

        boolean failure = false;

        for (Provider p: Security.getProviders()) {
            System.out.print(p.getName() + " ");
            if (p.getVersion() != 1.8d) {
                System.out.println("failed. " + "Version received was " +
                        p.getVersion());
                failure = true;
            } else {
                System.out.println("passed.");
            }
        }

        if (failure) {
            throw new Exception("Provider(s) failed to have the expected " +
                    "version value.");
        }
    }
 
Example 6
Source File: ProviderVersionCheck.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String arg[]) throws Exception{

        boolean failure = false;

        for (Provider p: Security.getProviders()) {
            System.out.print(p.getName() + " ");
            if (p.getVersion() != 9.0d) {
                System.out.println("failed. " + "Version received was " +
                        p.getVersion());
                failure = true;
            } else {
                System.out.println("passed.");
            }
        }

        if (failure) {
            throw new Exception("Provider(s) failed to have the expected " +
                    "version value.");
        }
    }
 
Example 7
Source File: ProviderList.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public ProviderList(GSSCaller caller, boolean useNative) {
    this.caller = caller;
    Provider[] provList;
    if (useNative) {
        provList = new Provider[1];
        provList[0] = new SunNativeProvider();
    } else {
        provList = Security.getProviders();
    }

    for (int i = 0; i < provList.length; i++) {
        Provider prov = provList[i];
        try {
            addProviderAtEnd(prov, null);
        } catch (GSSException ge) {
            // Move on to the next provider
            GSSUtil.debug("Error in adding provider " +
                          prov.getName() + ": " + ge);
        }
    } // End of for loop
}
 
Example 8
Source File: NoSync.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    for (Provider p : Security.getProviders()) {
        for (Provider.Service s : p.getServices()) {
            if (s.getType().equals("SecureRandom") &&
                    !s.getAlgorithm().contains("Block")) {
                test(SecureRandom.getInstance(s.getAlgorithm(), p));
            }
        }
    }
    Security.setProperty("securerandom.drbg.config", "HMAC_DRBG");
    test(SecureRandom.getInstance("DRBG"));
    Security.setProperty("securerandom.drbg.config", "CTR_DRBG");
    test(SecureRandom.getInstance("DRBG"));
}
 
Example 9
Source File: ShowAlgo.java    From snowblossom with Apache License 2.0 5 votes vote down vote up
public static void main(String args[])
{
  Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

  Provider[] p_a = Security.getProviders();
  for(Provider p : p_a)
  {
    System.out.println("Provider: " + p.toString());
    System.out.println("-----------------------------------");
    for(Provider.Service ps : p.getServices())
    {
      System.out.println("  " + ps.toString());
    }
  }
}
 
Example 10
Source File: SslUtils.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Registers Bouncy Castle (BC) as <em>first security provider</em> before any other providers 
 * coming with the Java runtime. This is done once, if not already applied.
 * <br>ATS calls this method internally when it is supposed to be needed.
 * 
 * <br><br><b>Note:</b> This is a static operation. All working threads will be affected.
 * The method itself is not thread-safe.
 * 
 * <br><br><b>Note:</b> Effective set of provider is done only once per Java runtime.
 *   Currently subsequent invocations do not check whether provider is removed meanwhile and 
 *   this way could be forcefully set other security provider.  
 */
public static void registerBCProvider() {

    if (bcProviderAlreadyRegisteredAsFirst) {
        return; // do nothing. Provider is already registered as first one.
    }

    boolean needToInsert = true;
    boolean needToRemove = false;

    Provider[] providers = Security.getProviders();
    for (int i = 0; i < providers.length; i++) {
        if (providers[i].getName().equalsIgnoreCase(BouncyCastleProvider.PROVIDER_NAME)) {
            if (i == 0) {
                needToInsert = false;
            } else {
                needToRemove = true;
            }
            break;
        }
    }

    if (needToInsert) {
        if (needToRemove) {
            Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
        }
        Provider bcProvider = new BouncyCastleProvider();
        Security.insertProviderAt(bcProvider, 1);
        bcProviderAlreadyRegisteredAsFirst = true;
        log.info("Bouncy Castle security provider is registered as first in the list of available providers");

        origKeystoreType = Security.getProperty("keystore.type");

        Security.setProperty("keystore.type", "jks");
        log.info("Default keystore type set to: JKS");
    }
}
 
Example 11
Source File: GetProviders.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    try {
        Provider[] providers1 = Security.getProviders();
        System.out.println("Amount of providers1: " + providers1.length);

        Provider[] providers2 = Security.getProviders(serviceAlgFilter);
        System.out.println("Amount of providers2: " + providers2.length);

        Map<String, String> filter = new HashMap<String, String>();
        filter.put(serviceAlgFilter, "");
        Provider[] providers3 = Security.getProviders(filter);
        System.out.println("Amount of providers3: " + providers3.length);

        Provider[] emptyProv1 = Security.getProviders(emptyServAlgFilter);
        if (emptyProv1 != null) {
            throw new RuntimeException("Empty Filter returned: " +
                emptyProv1.length + " providers");
        }
        System.out.println("emptyProv1 is empty as expected");

        Map<String, String> emptyFilter = new HashMap<String, String>();
        emptyFilter.put(emptyServAlgFilter, "");
        Provider[] emptyProv2 = Security.getProviders(emptyFilter);
        if (emptyProv2 != null) {
            throw new RuntimeException("Empty Filter returned: " +
                emptyProv2.length + " providers");
        }
        System.out.println("emptyProv2 is empty as expected");

    } catch(ExceptionInInitializerError e) {
        e.printStackTrace(System.out);
        throw new RuntimeException("Provider initialization error due to "
                + e.getCause());
    }
    System.out.println("Test passed");
}
 
Example 12
Source File: HttpsProtocolSupport.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private static boolean hasProvider( Class providerClass ) {
    Provider[] list = Security.getProviders();
    for (int i = 0; i < list.length; i++) {
        if (list[i].getClass().equals( providerClass )) return true;
    }
    return false;
}
 
Example 13
Source File: Platform.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
/**
 * Select the first recognized security provider according to the preference order returned by
 * {@link Security#getProviders}. If a recognized provider is not found then warn but continue.
 */
private static Provider getAndroidSecurityProvider() {
  Provider[] providers = Security.getProviders();
  for (Provider availableProvider : providers) {
    for (String providerClassName : ANDROID_SECURITY_PROVIDERS) {
      if (providerClassName.equals(availableProvider.getClass().getName())) {
        logger.log(Level.FINE, "Found registered provider {0}", providerClassName);
        return availableProvider;
      }
    }
  }
  logger.log(Level.WARNING, "Unable to find Conscrypt");
  return null;
}
 
Example 14
Source File: SpiEngUtils.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Verification: is algorithm supported or not
 *
 * @param algorithm
 * @param service
 * @return
 */
public static Provider isSupport(String algorithm, String service) {
    try {
        Provider[] provs = Security.getProviders(service.concat(".")
                .concat(algorithm));
        if (provs == null) {
            return null;
        }
        return (provs.length == 0 ? null : provs[0]);
    } catch (Exception e) {
        return null;
    }
}
 
Example 15
Source File: ProvidersSnapshot.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
private ProvidersSnapshot() {
    oldProviders = Security.getProviders();
}
 
Example 16
Source File: PRNGFixes.java    From DeviceConnect-Android with MIT License 4 votes vote down vote up
/**
 * Installs a Linux PRNG-backed {@code SecureRandom} implementation as the
 * default. Does nothing if the implementation is already the default or if
 * there is not need to install the implementation.
 *
 * @throws SecurityException if the fix is needed but could not be applied.
 */
private static void installLinuxPRNGSecureRandom()
        throws SecurityException {
    if (Build.VERSION.SDK_INT > VERSION_CODE_JELLY_BEAN_MR2) {
        // No need to apply the fix
        return;
    }

    // Install a Linux PRNG-based SecureRandom implementation as the
    // default, if not yet installed.
    Provider[] secureRandomProviders =
            Security.getProviders("SecureRandom.SHA1PRNG");
    if ((secureRandomProviders == null)
            || (secureRandomProviders.length < 1)
            || (!LinuxPRNGSecureRandomProvider.class.equals(
                    secureRandomProviders[0].getClass()))) {
        Security.insertProviderAt(new LinuxPRNGSecureRandomProvider(), 1);
    }

    // Assert that new SecureRandom() and
    // SecureRandom.getInstance("SHA1PRNG") return a SecureRandom backed
    // by the Linux PRNG-based SecureRandom implementation.
    SecureRandom rng1 = new SecureRandom();
    if (!LinuxPRNGSecureRandomProvider.class.equals(
            rng1.getProvider().getClass())) {
        throw new SecurityException(
                "new SecureRandom() backed by wrong Provider: "
                        + rng1.getProvider().getClass());
    }

    SecureRandom rng2;
    try {
        rng2 = SecureRandom.getInstance("SHA1PRNG");
    } catch (NoSuchAlgorithmException e) {
        throw new SecurityException("SHA1PRNG not available", e);
    }
    if (!LinuxPRNGSecureRandomProvider.class.equals(
            rng2.getProvider().getClass())) {
        throw new SecurityException(
                "SecureRandom.getInstance(\"SHA1PRNG\") backed by wrong"
                + " Provider: " + rng2.getProvider().getClass());
    }
}
 
Example 17
Source File: ProvidersSnapshot.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
private ProvidersSnapshot() {
    oldProviders = Security.getProviders();
}
 
Example 18
Source File: PRNGFixes.java    From Silence with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Installs a Linux PRNG-backed {@code SecureRandom} implementation as the
 * default. Does nothing if the implementation is already the default or if
 * there is not need to install the implementation.
 *
 * @throws SecurityException if the fix is needed but could not be applied.
 */
private static void installLinuxPRNGSecureRandom()
    throws SecurityException {
  if (Build.VERSION.SDK_INT > VERSION_CODE_JELLY_BEAN_MR2) {
    // No need to apply the fix
    return;
  }

  // Install a Linux PRNG-based SecureRandom implementation as the
  // default, if not yet installed.
  Provider[] secureRandomProviders =
      Security.getProviders("SecureRandom.SHA1PRNG");
  if ((secureRandomProviders == null)
      || (secureRandomProviders.length < 1)
      || (!LinuxPRNGSecureRandomProvider.class.equals(
      secureRandomProviders[0].getClass()))) {
    Security.insertProviderAt(new LinuxPRNGSecureRandomProvider(), 1);
  }

  // Assert that new SecureRandom() and
  // SecureRandom.getInstance("SHA1PRNG") return a SecureRandom backed
  // by the Linux PRNG-based SecureRandom implementation.
  SecureRandom rng1 = new SecureRandom();
  if (!LinuxPRNGSecureRandomProvider.class.equals(
      rng1.getProvider().getClass())) {
    throw new SecurityException(
        "new SecureRandom() backed by wrong Provider: "
            + rng1.getProvider().getClass());
  }

  SecureRandom rng2;
  try {
    rng2 = SecureRandom.getInstance("SHA1PRNG");
  } catch (NoSuchAlgorithmException e) {
    throw new SecurityException("SHA1PRNG not available", e);
  }
  if (!LinuxPRNGSecureRandomProvider.class.equals(
      rng2.getProvider().getClass())) {
    throw new SecurityException(
        "SecureRandom.getInstance(\"SHA1PRNG\") backed by wrong"
            + " Provider: " + rng2.getProvider().getClass());
  }
}
 
Example 19
Source File: Sasl.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
private static Set<Object> getFactories(String serviceName) {
    HashSet<Object> result = new HashSet<Object>();

    if ((serviceName == null) || (serviceName.length() == 0) ||
        (serviceName.endsWith("."))) {
        return result;
    }


    Provider[] providers = Security.getProviders();
    HashSet<String> classes = new HashSet<String>();
    Object fac;

    for (int i = 0; i < providers.length; i++) {
        classes.clear();

        // Check the keys for each provider.
        for (Enumeration<Object> e = providers[i].keys(); e.hasMoreElements(); ) {
            String currentKey = (String)e.nextElement();
            if (currentKey.startsWith(serviceName)) {
                // We should skip the currentKey if it contains a
                // whitespace. The reason is: such an entry in the
                // provider property contains attributes for the
                // implementation of an algorithm. We are only interested
                // in entries which lead to the implementation
                // classes.
                if (currentKey.indexOf(" ") < 0) {
                    String className = providers[i].getProperty(currentKey);
                    if (!classes.contains(className)) {
                        classes.add(className);
                        try {
                            fac = loadFactory(providers[i], className);
                            if (fac != null) {
                                result.add(fac);
                            }
                        }catch (Exception ignore) {
                        }
                    }
                }
            }
        }
    }
    return Collections.unmodifiableSet(result);
}
 
Example 20
Source File: ProvidersSnapshot.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
private ProvidersSnapshot() {
    oldProviders = Security.getProviders();
}