Esempio n. 1
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);
   }
 }
Esempio n. 2
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);
   }
 }
  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");
  }
 private static void checkProviderInfoEntries(Provider p) throws Exception {
   String value = (String) p.get("Provider.id name");
   if (!SampleProvider.NAME.equalsIgnoreCase(value) || !p.getName().equalsIgnoreCase(value)) {
     throw new Exception("Test Failed: incorrect name!");
   }
   value = (String) p.get("Provider.id info");
   if (!SampleProvider.INFO.equalsIgnoreCase(value) || !p.getInfo().equalsIgnoreCase(value)) {
     throw new Exception("Test Failed: incorrect info!");
   }
   value = (String) p.get("Provider.id className");
   if (!p.getClass().getName().equalsIgnoreCase(value)) {
     throw new Exception("Test Failed: incorrect className!");
   }
   double dvalue = Double.parseDouble((String) p.get("Provider.id version"));
   if ((SampleProvider.VERSION != dvalue) || p.getVersion() != dvalue) {
     throw new Exception("Test Failed: incorrect version!");
   }
   System.out.println("Test Passed");
 }
Esempio n. 5
0
 private static Object findImplEngine(final String baseName, String algorithm) {
   final Provider bcProvider = securityProvider;
   String alias;
   while ((alias = bcProvider.getProperty("Alg.Alias." + baseName + "." + algorithm)) != null) {
     algorithm = alias;
   }
   final String className = bcProvider.getProperty(baseName + "." + algorithm);
   if (className != null) {
     try {
       Class klass;
       ClassLoader loader = bcProvider.getClass().getClassLoader();
       if (loader != null) {
         klass = loader.loadClass(className);
       } else {
         klass = Class.forName(className);
       }
       return klass.newInstance();
     } catch (ClassNotFoundException e) {
       throw new IllegalStateException(
           "algorithm "
               + algorithm
               + " in provider "
               + bcProvider.getName()
               + " but no class \""
               + className
               + "\" found!");
     } catch (Exception e) {
       throw new IllegalStateException(
           "algorithm "
               + algorithm
               + " in provider "
               + bcProvider.getName()
               + " but class \""
               + className
               + "\" inaccessible!");
     }
   }
   return null;
 }
Esempio n. 6
0
  /**
   * Makes sure all all expected implementations (but not aliases) and that there are no extras,
   * according to what we expect from StandardNames
   */
  public void test_Provider_getServices() throws Exception {

    // build set of expected algorithms
    Map<String, Set<String>> remaining =
        new HashMap<String, Set<String>>(StandardNames.PROVIDER_ALGORITHMS);
    for (Entry<String, Set<String>> entry : remaining.entrySet()) {
      entry.setValue(new HashSet<String>(entry.getValue()));
    }

    List<String> extra = new ArrayList();
    List<String> missing = new ArrayList();

    Provider[] providers = Security.getProviders();
    for (Provider provider : providers) {
      String providerName = provider.getName();
      // ignore BouncyCastle provider if it is installed on the RI
      if (StandardNames.IS_RI && providerName.equals("BC")) {
        continue;
      }
      Set<Provider.Service> services = provider.getServices();
      assertNotNull(services);
      assertFalse(services.isEmpty());

      for (Provider.Service service : services) {
        String type = service.getType();
        String algorithm = service.getAlgorithm().toUpperCase();
        String className = service.getClassName();
        if (false) {
          System.out.println(providerName + " " + type + " " + algorithm + " " + className);
        }

        // remove from remaining, assert unknown if missing
        Set<String> algorithms = remaining.get(type);
        if (algorithms == null || !algorithms.remove(algorithm)) {
          // seems to be missing, but sometimes the same
          // algorithm is available from multiple providers
          // (e.g. KeyFactory RSA is available from
          // SunRsaSign and SunJSSE), so double check in
          // original source before giving error
          if (!(StandardNames.PROVIDER_ALGORITHMS.containsKey(type)
              && StandardNames.PROVIDER_ALGORITHMS.get(type).contains(algorithm))) {
            extra.add("Unknown " + type + " " + algorithm + " " + providerName + "\n");
          }
        }
        if (algorithms != null && algorithms.isEmpty()) {
          remaining.remove(type);
        }

        // make sure class exists and can be initialized
        try {
          assertNotNull(Class.forName(className, true, provider.getClass().getClassLoader()));
        } catch (ClassNotFoundException e) {
          // Sun forgot their own class
          if (!className.equals("sun.security.pkcs11.P11MAC")) {
            missing.add(className);
          }
        }
      }
    }

    // assert that we don't have any extra in the implementation
    Collections.sort(extra); // sort so that its grouped by type
    assertEquals("Extra algorithms", Collections.EMPTY_LIST, extra);

    // assert that we don't have any missing in the implementation
    assertEquals("Missing algorithms", Collections.EMPTY_MAP, remaining);

    // assert that we don't have any missing classes
    Collections.sort(missing); // sort it for readability
    assertEquals("Missing classes", Collections.EMPTY_LIST, missing);
  }
Esempio n. 7
0
  /**
   * Makes sure all provider properties either point to a class implementation that exists or are
   * aliases to known algorithms.
   */
  public void test_Provider_Properties() throws Exception {
    /*
     * A useful reference on Provider properties
     * <a href="http://java.sun.com/javase/6/docs/technotes/guides/security/crypto/HowToImplAProvider.html>
     * How to Implement a Provider in the Java &trade; Cryptography Architecture
     * </a>
     */

    Provider[] providers = Security.getProviders();
    for (Provider provider : providers) {
      // check Provider.id proprieties
      assertEquals(provider.getName(), provider.get("Provider.id name"));
      assertEquals(String.valueOf(provider.getVersion()), provider.get("Provider.id version"));
      assertEquals(provider.getInfo(), provider.get("Provider.id info"));
      assertEquals(provider.getClass().getName(), provider.get("Provider.id className"));

      // build map of all known aliases and implementations
      Map<String, String> aliases = new HashMap<String, String>();
      Map<String, String> implementations = new HashMap<String, String>();
      for (Entry<Object, Object> entry : provider.entrySet()) {
        Object k = entry.getKey();
        Object v = entry.getValue();
        assertEquals(String.class, k.getClass());
        assertEquals(String.class, v.getClass());
        String key = (String) k;
        String value = (String) v;

        // skip Provider.id keys, we check well known ones values above
        if (key.startsWith("Provider.id ")) {
          continue;
        }

        // skip property settings such as: "Signature.SHA1withDSA ImplementedIn" "Software"
        if (key.indexOf(' ') != -1) {
          continue;
        }

        Matcher m = alias.matcher(key);
        if (m.find()) {
          String type = m.group(1);
          aliases.put(key, type + "." + value);
        } else {
          implementations.put(key, value);
        }
      }

      // verify implementation classes are available
      for (Entry<String, String> entry : implementations.entrySet()) {
        String typeAndAlgorithm = entry.getKey();
        String className = entry.getValue();
        try {
          assertNotNull(Class.forName(className, true, provider.getClass().getClassLoader()));
        } catch (ClassNotFoundException e) {
          // Sun forgot their own class
          if (!className.equals("sun.security.pkcs11.P11MAC")) {
            fail("Could not find class " + className + " for " + typeAndAlgorithm);
          }
        }
      }

      // make sure all aliases point to some known implementation
      for (Entry<String, String> entry : aliases.entrySet()) {
        String alias = entry.getKey();
        String actual = entry.getValue();
        assertTrue(
            "Could not find implementation " + actual + " for alias " + alias,
            implementations.containsKey(actual));
      }
    }
  }
Esempio n. 8
0
  public static void main(String[] args) throws Exception {

    // Dynamically register the SunMSCAPI provider
    Security.addProvider(new sun.security.mscapi.SunMSCAPI());

    Provider p = Security.getProvider("SunMSCAPI");

    System.out.println("SunMSCAPI provider classname is " + p.getClass().getName());
    System.out.println("SunMSCAPI provider name is " + p.getName());
    System.out.println("SunMSCAPI provider version # is " + p.getVersion());
    System.out.println("SunMSCAPI provider info is " + p.getInfo());

    /*
     * Secure Random
     */
    SecureRandom random = SecureRandom.getInstance("Windows-PRNG", p);
    System.out.println("    Windows-PRNG is implemented by: " + random.getClass().getName());

    /*
     * Key Store
     */
    KeyStore keystore = KeyStore.getInstance("Windows-MY", p);
    System.out.println("    Windows-MY is implemented by: " + keystore.getClass().getName());

    keystore = KeyStore.getInstance("Windows-ROOT", p);
    System.out.println("    Windows-ROOT is implemented by: " + keystore.getClass().getName());

    /*
     * Signature
     */
    Signature signature = Signature.getInstance("SHA1withRSA", p);
    System.out.println("    SHA1withRSA is implemented by: " + signature.getClass().getName());

    signature = Signature.getInstance("MD5withRSA", p);
    System.out.println("    MD5withRSA is implemented by: " + signature.getClass().getName());

    signature = Signature.getInstance("MD2withRSA", p);
    System.out.println("    MD2withRSA is implemented by: " + signature.getClass().getName());

    /*
     * Key Pair Generator
     */
    KeyPairGenerator keypairGenerator = KeyPairGenerator.getInstance("RSA", p);
    System.out.println("    RSA is implemented by: " + keypairGenerator.getClass().getName());

    /*
     * Cipher
     */
    Cipher cipher = null;

    try {
      cipher = Cipher.getInstance("RSA", p);
      System.out.println("    RSA is implemented by: " + cipher.getClass().getName());

      cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", p);
      System.out.println(
          "    RSA/ECB/PKCS1Padding is implemented by: " + cipher.getClass().getName());

    } catch (GeneralSecurityException e) {
      System.out.println("Cipher not supported by provider, skipping...");
    }
  }
  /**
   * Replacement for JCA/JCE's {@link javax.crypto.Cipher#getInstance}. The original method only
   * accepts JCE providers from signed jars, which prevents us from bundling our cryptography
   * provider Bouncy Caster with the application.
   *
   * @param transformation the transformation to find an implementation for
   */
  public static Cipher getCipher(final String transformation) {
    try {
      /* Split the transformation into algorithm, mode and padding */

      final Matcher transformation_matcher =
          s_transformation_pattern.matcher(transformation.toUpperCase());
      if (!transformation_matcher.matches())
        throw new RuntimeException("Transformation " + transformation + " is invalid");

      final String algorithm = transformation_matcher.group(1);
      final String mode = transformation_matcher.group(3);
      final String padding = transformation_matcher.group(4);
      final boolean isBareAlgorithm = (mode == null) && (padding == null);

      /* Build the property values we need to search for. */

      final String algorithmModePadding =
          !isBareAlgorithm ? algorithm + "/" + mode + "/" + padding : null;
      final String algorithmMode = !isBareAlgorithm ? algorithm + "/" + mode : null;
      final String algorithmPadding = !isBareAlgorithm ? algorithm + "//" + padding : null;

      /* Search the provider for implementations. We ask for more specific (i.e matching
       * the requested mode and or padding) implementation first, then fall back to more
       * generals ones which we then must configure for the mode and padding.
       */

      final CipherSpi cipherSpi;

      if (!isBareAlgorithm && (resolveProperty(Provider, "Cipher", algorithmModePadding) != null)) {
        @SuppressWarnings("unchecked")
        final Class<? extends CipherSpi> cipherSpiClass =
            (Class<? extends CipherSpi>)
                Class.forName(resolveProperty(Provider, "Cipher", algorithmModePadding));
        cipherSpi = cipherSpiClass.newInstance();
      } else if (!isBareAlgorithm && (resolveProperty(Provider, "Cipher", algorithmMode) != null)) {
        @SuppressWarnings("unchecked")
        final Class<? extends CipherSpi> cipherSpiClass =
            (Class<? extends CipherSpi>)
                Class.forName(resolveProperty(Provider, "Cipher", algorithmMode));
        cipherSpi = cipherSpiClass.newInstance();
        if (!isBareAlgorithm) cipherSpiSetPadding(cipherSpi, padding);
      } else if (!isBareAlgorithm
          && (resolveProperty(Provider, "Cipher", algorithmPadding) != null)) {
        @SuppressWarnings("unchecked")
        final Class<? extends CipherSpi> cipherSpiClass =
            (Class<? extends CipherSpi>)
                Class.forName(resolveProperty(Provider, "Cipher", algorithmPadding));
        cipherSpi = cipherSpiClass.newInstance();
        if (!isBareAlgorithm) cipherSpiSetMode(cipherSpi, mode);
      } else if (resolveProperty(Provider, "Cipher", algorithm) != null) {
        @SuppressWarnings("unchecked")
        final Class<? extends CipherSpi> cipherSpiClass =
            (Class<? extends CipherSpi>)
                Class.forName(resolveProperty(Provider, "Cipher", algorithm));
        cipherSpi = cipherSpiClass.newInstance();
        if (!isBareAlgorithm) {
          cipherSpiSetMode(cipherSpi, mode);
          cipherSpiSetPadding(cipherSpi, padding);
        }
      } else {
        throw new RuntimeException(
            "Provider "
                + Provider.getName()
                + " ("
                + Provider.getClass()
                + ") does not implement "
                + transformation);
      }

      /* Create a {@link javax.crypto.Cipher} instance from the {@link javax.crypto.CipherSpi} the provider gave us */

      s_logger.info("Using SPI " + cipherSpi.getClass() + " for " + transformation);
      return getCipher(cipherSpi, transformation.toUpperCase());
    } catch (final RuntimeException e) {
      throw e;
    } catch (final Error e) {
      throw e;
    } catch (final Throwable e) {
      throw new RuntimeException(
          "Provider "
              + Provider.getName()
              + " ("
              + Provider.getClass()
              + ") failed to instanciate "
              + transformation,
          e);
    }
  }
Esempio n. 10
0
 ProviderConfig(Provider provider) {
   this.className = provider.getClass().getName();
   this.argument = "";
   this.provider = provider;
 }