static {
   for (Provider provider : Security.getProviders()) {
     if (provider.getName().startsWith("SunPKCS11")) {
       Security.removeProvider(provider.getName());
     }
   }
 }
示例#2
0
  public String getSecurityProviders() {
    StringBuilder sb = new StringBuilder();
    Provider[] p = Security.getProviders();

    for (Provider provider : p) {
      sb.append(provider.getName())
          .append("   ")
          .append(provider.getVersion())
          .append("   ")
          .append(provider.getInfo())
          .append("<br>");
    }

    Set<String> s = Security.getAlgorithms("MessageDigest");
    for (String string : s) {
      sb.append(string).append("   ");
    }

    sb.append(Integer.toBinaryString(7))
        .append("   ")
        .append(Integer.toOctalString(15))
        .append("   ")
        .append(Integer.toHexString(17));

    return sb.toString();
  }
示例#3
0
 protected SaslServerFactory findSaslServerFactory(final boolean wildFlyProvider)
     throws Exception {
   Provider p = findProvider("SaslServerFactory.GSSAPI", wildFlyProvider);
   String factoryName = (String) p.get("SaslServerFactory.GSSAPI");
   return (SaslServerFactory)
       BaseGssapiTests.class.getClassLoader().loadClass(factoryName).newInstance();
 }
示例#4
0
  /**
   * see if we can find an algorithm (or its alias and what it represents) in the property table for
   * the given provider.
   *
   * @return null if no algorithm found, an Implementation if it is.
   */
  static Implementation getImplementation(
      String baseName, String algorithm, Provider prov, Class[] ctorparamtype, Object[] ctorparam)
      throws InvalidAlgorithmParameterException {
    String alias;

    while ((alias = prov.getProperty("Alg.Alias." + baseName + "." + algorithm)) != null) {
      algorithm = alias;
    }

    String className = prov.getProperty(baseName + "." + algorithm);

    if (className != null) {
      try {
        return new Implementation(
            Class.forName(className).getConstructor(ctorparamtype).newInstance(ctorparam), prov);
      } catch (ClassNotFoundException e) {
        throw new IllegalStateException(
            "algorithm " + algorithm + " in provider " + prov.getName() + " but no class found!");
      } catch (Exception e) {
        if (e instanceof InvalidAlgorithmParameterException) {
          throw (InvalidAlgorithmParameterException) e;
        }

        throw new IllegalStateException(
            "algorithm "
                + algorithm
                + " in provider "
                + prov.getName()
                + " but class inaccessible!");
      }
    }

    return null;
  }
 @Override
 public HttpServerAuthenticationMechanism createAuthenticationMechanism(
     String mechanismName, Map<String, ?> properties, CallbackHandler callbackHandler) {
   for (Provider current : providers.get()) {
     Set<Service> services = current.getServices();
     if (services != null) {
       for (Service currentService : services) {
         if (SERVICE_TYPE.equals(currentService.getType())) {
           try {
             HttpServerAuthenticationMechanismFactory factory =
                 (HttpServerAuthenticationMechanismFactory) currentService.newInstance(null);
             HttpServerAuthenticationMechanism mechanism =
                 factory.createAuthenticationMechanism(mechanismName, properties, callbackHandler);
             if (mechanism != null) {
               return mechanism;
             }
           } catch (NoSuchAlgorithmException e) {
             log.debug(e);
           }
         }
       }
     }
   }
   return null;
 }
  /**
   * return a more "meaningful" representation for the signature algorithm used in the certficate.
   */
  public String getSigAlgName() {
    Provider prov = Security.getProvider(BouncyCastleProvider.PROVIDER_NAME);

    if (prov != null) {
      String algName = prov.getProperty("Alg.Alias.Signature." + this.getSigAlgOID());

      if (algName != null) {
        return algName;
      }
    }

    Provider[] provs = Security.getProviders();

    //
    // search every provider looking for a real algorithm
    //
    for (int i = 0; i != provs.length; i++) {
      String algName = provs[i].getProperty("Alg.Alias.Signature." + this.getSigAlgOID());
      if (algName != null) {
        return algName;
      }
    }

    return this.getSigAlgOID();
  }
示例#7
0
 private void premain(Provider p) throws Exception {
   long start = System.currentTimeMillis();
   System.out.println("Running test with provider " + p.getName() + "...");
   main(p);
   long stop = System.currentTimeMillis();
   System.out.println(
       "Completed test with provider " + p.getName() + " (" + (stop - start) + " ms).");
 }
示例#8
0
文件: App.java 项目: henrysolo/java
 /** 获取当前所有提供者 */
 public static void getAllProviders() {
   for (Provider provider : Security.getProviders()) {
     System.out.println("provider name:" + provider.getName());
     for (Map.Entry<Object, Object> map : provider.entrySet()) {
       System.out.println("key=" + map.getKey());
       System.out.println("value=" + map.getValue());
     }
   }
 }
 /**
  * Returns the value attached to a provider property.
  *
  * <p>Supports aliases, i.e. if there is no property named type.name but one named
  * Alg.Alias.type.name, the value of Alg.Alias.type.name is assumed to be the <b>name</b> of the
  * actual property.
  *
  * @param provider JCE provider
  * @param type type (Cipher, Algorithm, ...)
  * @param name transformation
  * @return the properties value which usually is the implementing class'es name
  */
 private static String resolveProperty(
     final Provider provider, final String type, final String name) {
   if (Provider.getProperty(type + "." + name) != null)
     return Provider.getProperty(type + "." + name);
   else if (Provider.getProperty("Alg.Alias." + type + "." + name) != null)
     return resolveProperty(
         provider, type, Provider.getProperty("Alg.Alias." + type + "." + name));
   else return null;
 }
 /**
  * Inizializza il Verificatore passandogli come parametro la busta crittografica di cui deve
  * verificare la firma
  *
  * @param signedData la busta crittografica da controllare
  * @param token Il token crittografico contenente i certicati di ROOT utilizzati dal verificatore
  *     per verificare l'affidabilità dei certificati dei firmatari
  */
 CadesBESVerifier(CMSSignedData signedData, CRToken token) {
   // inizializza il provider di Bouncy Castle
   Provider p1 = new BouncyCastleProvider();
   Security.addProvider(p1);
   this.bcProvName = p1.getName();
   this.signedData = signedData;
   if (this.signedData == null) throw new NullPointerException();
   if (token != null) this.token = token;
   this.certStore = this.signedData.getCertificates();
 }
 /**
  * Get a password factory instance. The returned password factory object will implement the given
  * algorithm.
  *
  * @param algorithm the name of the algorithm
  * @param providerSupplier the provider supplier to search
  * @return a password factory instance
  * @throws NoSuchAlgorithmException if the given algorithm has no available implementations
  */
 public static PasswordFactory getInstance(String algorithm, Supplier<Provider[]> providerSupplier)
     throws NoSuchAlgorithmException {
   for (Provider provider : providerSupplier.get()) {
     final Provider.Service service = provider.getService("PasswordFactory", algorithm);
     if (service != null) {
       return new PasswordFactory(
           (PasswordFactorySpi) service.newInstance(null), provider, algorithm);
     }
   }
   throw log.noSuchAlgorithmInvalidAlgorithm(algorithm);
 }
 static Provider findProvider(String name) {
   Provider[] providers = Security.getProviders();
   Provider registeredProvider = null;
   for (Provider provider : providers) {
     if (name.equals(provider.getName())) {
       registeredProvider = provider;
       break;
     }
   }
   return registeredProvider;
 }
示例#13
0
  public static void testDefault(PKCS11Test test) throws Exception {
    // run test for default configured PKCS11 providers (if any)

    if ("true".equals(System.getProperty("NO_DEFAULT"))) {
      return;
    }

    Provider[] providers = Security.getProviders();
    for (int i = 0; i < providers.length; i++) {
      Provider p = providers[i];
      if (p.getName().startsWith("SunPKCS11-")) {
        test.premain(p);
      }
    }
  }
示例#14
0
 private static MessageDigest findAlternativeMessageDigest() {
   if ("MD5".equals(hashAlgorithm)) {
     for (Provider provider : Security.getProviders()) {
       for (Provider.Service service : provider.getServices()) {
         hashAlgorithm = service.getAlgorithm();
         try {
           MessageDigest messageDigest = MessageDigest.getInstance(hashAlgorithm);
           if (messageDigest != null) return messageDigest;
         } catch (NoSuchAlgorithmException ignored) {
         }
       }
     }
   }
   return null;
 }
示例#15
0
 /*
  * Verify that the provider JAR files are signed properly, which
  * means the signer's certificate can be traced back to a
  * JCE trusted CA.
  * Return null if ok, failure Exception if verification failed.
  */
 static synchronized Exception getVerificationResult(Provider p) {
   Object o = verificationResults.get(p);
   if (o == PROVIDER_VERIFIED) {
     return null;
   } else if (o != null) {
     return (Exception) o;
   }
   if (verifyingProviders.get(p) != null) {
     // this method is static synchronized, must be recursion
     // return failure now but do not save the result
     return new NoSuchProviderException("Recursion during verification");
   }
   try {
     verifyingProviders.put(p, Boolean.FALSE);
     URL providerURL = getCodeBase(p.getClass());
     verifyProviderJar(providerURL);
     // Verified ok, cache result
     verificationResults.put(p, PROVIDER_VERIFIED);
     return null;
   } catch (Exception e) {
     verificationResults.put(p, e);
     return e;
   } finally {
     verifyingProviders.remove(p);
   }
 }
示例#16
0
 // Forms new instance of factory
 @DSSafe(DSCat.SAFE_LIST)
 @DSGenerator(
     tool_name = "Doppelganger",
     tool_version = "2.0",
     generated_on = "2014-09-03 15:00:08.675 -0400",
     hash_original_method = "A22E26D7D508455A024AA2A1D979B72B",
     hash_generated_method = "95A1D0DF36A51AD50595EF2DE46F3F97")
 private static Object newInstance(String factoryName, Provider prv) throws SaslException {
   String msg = "auth.31"; // $NON-NLS-1$
   Object factory;
   ClassLoader cl = prv.getClass().getClassLoader();
   if (cl == null) {
     cl = ClassLoader.getSystemClassLoader();
   }
   try {
     factory = (Class.forName(factoryName, true, cl)).newInstance();
     return factory;
   } catch (IllegalAccessException e) {
     throw new SaslException(msg + factoryName, e);
   } catch (ClassNotFoundException e) {
     throw new SaslException(msg + factoryName, e);
   } catch (InstantiationException e) {
     throw new SaslException(msg + factoryName, e);
   }
 }
示例#17
0
 // NOTE: none (at least for BC 1.47)
 private static String getSecureRandomAlgorithm(final Provider provider) {
   for (Provider.Service service : provider.getServices()) {
     if ("SecureRandom".equals(service.getType())) {
       return service.getAlgorithm();
     }
   }
   return null;
 }
  public static void main(String[] args) throws Exception {

    Provider p = new com.sun.exp.provider.EXP();
    Security.insertProviderAt(p, 1);

    Object[] signers = p.getClass().getSigners();
    if (signers == null || signers.length <= 0) {
      throw new SecurityException("Test Failed");
    } else {
      for (int i = 0; i < signers.length; i++) {
        System.out.println("signer [" + i + "] = " + signers[i]);
      }
    }

    MessageDigest md = MessageDigest.getInstance("SHA1");
    System.out.println("test passed");
  }
示例#19
0
 @Test
 public void testDecryptDataThrowsNullPointerException() throws Throwable {
   try {
     new JCEHandler((Provider) null).decryptData("testString".getBytes(), null);
     fail("Expected NullPointerException to be thrown");
   } catch (NullPointerException ex) {
     assertNull("ex.getMessage()", ex.getMessage());
   }
 }
示例#20
0
  /**
   * see if we can find an algorithm (or its alias and what it represents) in the property table for
   * the given provider.
   *
   * @return null if no algorithm found, an Implementation if it is.
   */
  static Implementation getImplementation(String baseName, String algorithm, Provider prov) {
    if (prov == null) {
      Provider[] provider = Security.getProviders();

      //
      // search every provider looking for the algorithm we want.
      //
      for (int i = 0; i != provider.length; i++) {
        Implementation imp = getImplementation(baseName, algorithm, provider[i]);
        if (imp != null) {
          return imp;
        }
      }

      return null;
    }

    String alias;

    while ((alias = prov.getProperty("Alg.Alias." + baseName + "." + algorithm)) != null) {
      algorithm = alias;
    }

    String className = prov.getProperty(baseName + "." + algorithm);

    if (className != null) {
      try {
        return new Implementation(Class.forName(className).newInstance(), prov);
      } catch (ClassNotFoundException e) {
        throw new IllegalStateException(
            "algorithm " + algorithm + " in provider " + prov.getName() + " but no class found!");
      } catch (Exception e) {
        throw new IllegalStateException(
            "algorithm "
                + algorithm
                + " in provider "
                + prov.getName()
                + " but class inaccessible: "
                + e.toString());
      }
    }

    return null;
  }
示例#21
0
 @Test
 public void testEncryptDataThrowsNullPointerException() throws Throwable {
   byte[] data = new byte[1];
   try {
     new JCEHandler((Provider) null).encryptData(data, null);
     fail("Expected NullPointerException to be thrown");
   } catch (NullPointerException ex) {
     assertNull("ex.getMessage()", ex.getMessage());
   }
 }
示例#22
0
 @Test
 public void testGenerateDESKeyThrowsJCEHandlerException2() throws Throwable {
   try {
     new JCEHandler((Provider) null).generateDESKey((short) 65);
     fail("Expected JCEHandlerException to be thrown");
   } catch (JCEHandlerException ex) {
     assertEquals("ex.getMessage()", "java.lang.NullPointerException", ex.getMessage());
     assertNull("ex.getNested().getMessage()", ex.getNested().getMessage());
   }
 }
  private String[] getAvailableBuiltInDigestAlgorithmNames() {
    Set<String> algorithmsSet = new HashSet<String>();
    Provider[] providers = Security.getProviders();
    for (Provider provider : providers) {
      Set<Provider.Service> services = provider.getServices();
      for (Provider.Service service : services) {
        if (service.getType() == "MessageDigest") {
          algorithmsSet.add(service.getAlgorithm());
        }
      }
    }

    // For some reason my Java implementation gives SHA1 two names, so we will remove one.
    if (algorithmsSet.contains("SHA") && algorithmsSet.contains("SHA1")) {
      algorithmsSet.remove("SHA");
    }

    return algorithmsSet.toArray(new String[algorithmsSet.size()]);
  }
示例#24
0
 static Instance getInstance(String type, Class<?> clazz, String algorithm, Provider provider)
     throws NoSuchAlgorithmException {
   Service s = GetInstance.getService(type, algorithm, provider);
   Exception ve = JceSecurity.getVerificationResult(provider);
   if (ve != null) {
     String msg = "JCE cannot authenticate the provider " + provider.getName();
     throw new SecurityException(msg, ve);
   }
   return GetInstance.getInstance(s, clazz);
 }
示例#25
0
 @Test
 public void testDecryptDESKeyThrowsNullPointerException() throws Throwable {
   byte[] encryptedDESKey = new byte[2];
   try {
     new JCEHandler((Provider) null).decryptDESKey((short) 100, encryptedDESKey, null, true);
     fail("Expected NullPointerException to be thrown");
   } catch (NullPointerException ex) {
     assertNull("ex.getMessage()", ex.getMessage());
   }
 }
 @Override
 public int hashCode() {
   int result = super.hashCode();
   result = 31 * result + id.hashCode();
   result = 31 * result + (listName != null ? listName.hashCode() : 0);
   result = 31 * result + (listMembers != null ? listMembers.hashCode() : 0);
   result = 31 * result + (provider != null ? provider.hashCode() : 0);
   result = 31 * result + (providerId != null ? providerId.hashCode() : 0);
   return result;
 }
 @Override
 public String[] getMechanismNames(Map<String, ?> properties) {
   Set<String> mechanismNames = new LinkedHashSet<>();
   for (Provider current : providers.get()) {
     Set<Service> services = current.getServices();
     if (services != null) {
       for (Service currentService : services) {
         if (SERVICE_TYPE.equals(currentService.getType())) {
           try {
             String[] serviceMechNames =
                 ((HttpServerAuthenticationMechanismFactory) currentService.newInstance(null))
                     .getMechanismNames(properties);
             Collections.addAll(mechanismNames, serviceMechNames);
           } catch (NoSuchAlgorithmException e) {
             log.debug(e);
           }
         }
       }
     }
   }
   return mechanismNames.toArray(new String[mechanismNames.size()]);
 }
  @Override
  public void run() {
    Provider[] ps = java.security.Security.getProviders();
    for (Provider p : ps) {
      System.out.println("=========================================================");
      System.out.println(p);
      p.list(System.out);
    }

    try {
      System.out.println();
      System.out.println("=========================================================");
      System.out.println("a test of " + Properties.class);
      Properties ppt = new Properties();
      ppt.setProperty("hello", "world");
      ppt.list(System.out);
      ppt.store(System.out, "[some comments]");
      ppt.storeToXML(System.out, "[some comments]", "utf-8");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
示例#29
0
 @Test
 public void testEncryptDESKeyThrowsNullPointerException() throws Throwable {
   byte[] bytes = new byte[1];
   Key encryptingKey = new SecretKeySpec(bytes, "testJCEHandlerParam2");
   try {
     new JCEHandler((Provider) null).encryptDESKey((short) 100, null, encryptingKey);
     fail("Expected NullPointerException to be thrown");
   } catch (NullPointerException ex) {
     assertNull("ex.getMessage()", ex.getMessage());
     assertEquals(
         "(SecretKeySpec) encryptingKey.getAlgorithm()",
         "testJCEHandlerParam2",
         ((SecretKeySpec) encryptingKey).getAlgorithm());
   }
 }
示例#30
0
 void initiateProviderKeyStore(Provider provider) throws Exception {
   String prov = null;
   for (Provider.Service ps : provider.getServices()) {
     if (ps.getType().equals("KeyStore")) {
       prov = ps.getAlgorithm();
     }
   }
   Security.addProvider(provider);
   KeyStore ks = KeyStore.getInstance(prov, provider);
   ks.load(
       CMD_keystore.found ? new FileInputStream(CMD_keystore.getString()) : null,
       CMD_keypass.found ? CMD_keypass.getString().toCharArray() : null);
   wrap.setKeyStore(ks, CMD_keypass.getString());
   CMD_keystore.found = false;
 }