コード例 #1
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    javax.servlet.http.Cookie[] cookies = request.getCookies();

    String param = null;
    boolean foundit = false;
    if (cookies != null) {
      for (javax.servlet.http.Cookie cookie : cookies) {
        if (cookie.getName().equals("foo")) {
          param = cookie.getValue();
          foundit = true;
        }
      }
      if (!foundit) {
        // no cookie found in collection
        param = "";
      }
    } else {
      // no cookies
      param = "";
    }

    String bar;

    // Simple if statement that assigns param to bar on true condition
    int i = 196;
    if ((500 / 42) + i > 200) bar = param;
    else bar = "This should never happen";

    java.security.Provider[] provider = java.security.Security.getProviders();
    javax.crypto.Cipher c;

    try {
      if (provider.length > 1) {
        c =
            javax.crypto.Cipher.getInstance(
                "DES/CBC/PKCS5PADDING", java.security.Security.getProvider("SunJCE"));
      } else {
        c =
            javax.crypto.Cipher.getInstance(
                "DES/CBC/PKCS5PADDING", java.security.Security.getProvider("SunJCE"));
      }
    } catch (java.security.NoSuchAlgorithmException e) {
      System.out.println(
          "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case");
      throw new ServletException(e);
    } catch (javax.crypto.NoSuchPaddingException e) {
      System.out.println(
          "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case");
      throw new ServletException(e);
    }
    response
        .getWriter()
        .println(
            "Crypto Test javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) executed");
  }
コード例 #2
0
ファイル: SecurityHandler.java プロジェクト: ArcheonK/Spout
 static {
   Provider p = Security.getProvider("BC");
   if (p == null) {
     Security.addProvider(new BouncyCastleProvider());
     p = Security.getProvider("BC");
     if (p == null) {
       Spout.getLogger().info("Unable to start security provider");
     }
   }
   provider = p;
   instance = new SecurityHandler();
 }
コード例 #3
0
ファイル: Pomocnicza.java プロジェクト: pawelfree/b2btester
 @BeforeClass
 public static void setProvider() {
   provider = Security.getProvider("BC");
   if (provider == null) {
     try {
       Security.addProvider(new BouncyCastleProvider());
       provider = Security.getProvider("BC");
     } catch (Exception ex) {
       System.err.println("<setProvider> failed : " + ex.getMessage());
     }
   }
 }
コード例 #4
0
ファイル: RSATest.java プロジェクト: goldcoin/java-experiment
  private void oaepCompatibilityTest(String digest, PrivateKey privKey, PublicKey pubKey)
      throws Exception {
    if (Security.getProvider("SunJCE") == null || Security.getProvider("SunRsaSign") == null) {
      return;
    }

    KeyFactory fact = KeyFactory.getInstance("RSA", "SunRsaSign");
    PrivateKey priv2048Key = fact.generatePrivate(priv2048KeySpec);
    PublicKey pub2048Key = fact.generatePublic(pub2048KeySpec);

    byte[] data = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};

    Cipher sCipher;
    try {
      sCipher = Cipher.getInstance("RSA/ECB/OAEPWith" + digest + "AndMGF1Padding", "SunJCE");
    } catch (NoSuchAlgorithmException e) {
      return;
    } catch (NoSuchPaddingException e) {
      return;
    }

    sCipher.init(Cipher.ENCRYPT_MODE, pub2048Key);

    byte[] enctext = sCipher.doFinal(data);

    Cipher bcCipher = Cipher.getInstance("RSA/ECB/OAEPWith" + digest + "AndMGF1Padding", "BC");

    bcCipher.init(
        Cipher.DECRYPT_MODE,
        privKey,
        new OAEPParameterSpec(digest, "MGF1", MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT));

    byte[] plaintext = bcCipher.doFinal(enctext);

    if (!Arrays.areEqual(plaintext, data)) {
      fail("data did not decrypt first time");
    }

    bcCipher.init(
        Cipher.ENCRYPT_MODE,
        pubKey,
        new OAEPParameterSpec(digest, "MGF1", MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT));

    enctext = bcCipher.doFinal(data);

    sCipher.init(Cipher.DECRYPT_MODE, priv2048Key);

    plaintext = sCipher.doFinal(enctext);

    if (!Arrays.areEqual(plaintext, data)) {
      fail("data did not decrypt second time");
    }
  }
コード例 #5
0
 /**
  * Create an instance of the named key manager factory, from the named provider.
  *
  * @param algorithm The type of key manager factory to get.
  * @param provider The name of the provider to get the implementation from.
  * @return An appropriate implementation of that algorithm.
  * @throws NoSuchAlgorithmException If the provider does not implement the requested algorithm.
  * @throws NoSuchProviderException If the named provider does not exist.
  * @throws IllegalArgumentException if either <code>algorithm</code> or <code>provider</code> is
  *     <code>null</code>, or if <code>algorithm</code> is an empty string.
  */
 public static final KeyManagerFactory getInstance(String algorithm, String provider)
     throws NoSuchAlgorithmException, NoSuchProviderException {
   if (provider == null) throw new IllegalArgumentException("provider MUST NOT be null");
   Provider p = Security.getProvider(provider);
   if (p == null) throw new NoSuchProviderException(provider);
   return getInstance(algorithm, p);
 }
コード例 #6
0
  /**
   * 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
ファイル: CertUtil.java プロジェクト: fadossantos/bc-java
  /**
   * return an implementation for a given algorithm/provider. If the provider is null, we grab the
   * first avalaible who has the required algorithm.
   *
   * @return null if no algorithm found, an Implementation if it is.
   * @exception NoSuchProviderException if a provider is specified and not found.
   */
  static Implementation getImplementation(String baseName, String algorithm, String provider)
      throws NoSuchProviderException {
    if (provider == null) {
      Provider[] prov = Security.getProviders();

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

      if (prov == null) {
        throw new NoSuchProviderException("Provider " + provider + " not found");
      }

      return getImplementation(baseName, algorithm, prov);
    }

    return null;
  }
コード例 #8
0
 /**
  * Creates directory services and starts LDAP server
  *
  * @param managementClient
  * @param containerId
  * @throws Exception
  * @see
  *     org.jboss.as.arquillian.api.ServerSetupTask#setup(org.jboss.as.arquillian.container.ManagementClient,
  *     java.lang.String)
  */
 public void setup(ManagementClient managementClient, String containerId) throws Exception {
   try {
     if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
       Security.addProvider(new BouncyCastleProvider());
       removeBouncyCastle = true;
     }
   } catch (SecurityException ex) {
     LOGGER.warn("Cannot register BouncyCastleProvider", ex);
   }
   directoryService = DSAnnotationProcessor.getDirectoryService();
   DSAnnotationProcessor.injectEntries(
       directoryService,
       "dn: uid=jduke,dc=jboss,dc=org\n" //
           + "objectclass: top\n" //
           + "objectclass: uidObject\n" //
           + "objectclass: person\n" //
           + "uid: jduke\n" //
           + "cn: Java Duke\n" //
           + "sn: Duke\n" //
           + "userPassword: theduke\n");
   final ManagedCreateLdapServer createLdapServer =
       new ManagedCreateLdapServer(
           (CreateLdapServer) AnnotationUtils.getInstance(CreateLdapServer.class));
   Utils.fixApacheDSTransportAddress(
       createLdapServer, Utils.getSecondaryTestAddress(managementClient, false));
   ldapServer =
       ServerAnnotationProcessor.instantiateLdapServer(createLdapServer, directoryService);
   ldapServer.start();
 }
コード例 #9
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    org.owasp.benchmark.helpers.SeparateClassRequest scr =
        new org.owasp.benchmark.helpers.SeparateClassRequest(request);
    String param = scr.getTheParameter("foo");

    String bar = new Test().doSomething(param);

    java.security.Provider[] provider = java.security.Security.getProviders();
    javax.crypto.Cipher c;

    try {
      c =
          javax.crypto.Cipher.getInstance(
              "AES/CBC/PKCS5PADDING", java.security.Security.getProvider("SunJCE"));
    } catch (java.security.NoSuchAlgorithmException e) {
      System.out.println(
          "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case");
      throw new ServletException(e);
    } catch (javax.crypto.NoSuchPaddingException e) {
      System.out.println(
          "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case");
      throw new ServletException(e);
    }
    response
        .getWriter()
        .println(
            "Crypto Test javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) executed");
  } // end doPost
コード例 #10
0
  private List<KeyStore> initCAPIAddressBook() throws AOKeyStoreManagerException {
    if (!Platform.getOS().equals(Platform.OS.WINDOWS)) {
      throw new InvalidOSException("Microsoft Windows"); // $NON-NLS-1$
    }

    // Nos aseguramos de que SunMSCAPI este cargado, para que la DLL
    // sunmscapi.dll tambien lo este
    if (Security.getProvider("SunMSCAPI") == null) { // $NON-NLS-1$
      try {
        Security.addProvider(
            (Provider) Class.forName("sun.security.mscapi.SunMSCAPI").newInstance()); // $NON-NLS-1$
      } catch (final Exception e) {
        throw new MissingSunMSCAPIException(e);
      }
    }
    Provider p = Security.getProvider("MSCAPIAddressBook"); // $NON-NLS-1$
    if (p == null) {
      try {
        p =
            (Provider)
                Class.forName("es.gob.afirma.keystores.capiaddressbook.MSCAPIAddressBook")
                    .newInstance(); //$NON-NLS-1$
      } catch (final Exception e) {
        throw new MissingLibraryException(
            "No se ha podido instanciar el proveedor MSCAPIAddressBook", e); // $NON-NLS-1$
      }
      Security.addProvider(p);
    }

    try {
      this.ks = KeyStore.getInstance(this.ksType.getProviderName(), p);
    } catch (final Exception e) {
      throw new AOKeyStoreManagerException(
          "No se ha podido obtener el almacen MSCAPIAddressBook.ADDRESSBOOK", e); // $NON-NLS-1$
    }

    try {
      this.ks.load(null, null);
    } catch (final Exception e) {
      throw new AOKeyStoreManagerException(
          "No se ha podido abrir el almacen MSCAPIAddressBook.ADDRESSBOOK", e); // $NON-NLS-1$
    }

    final List<KeyStore> ret = new ArrayList<KeyStore>(1);
    ret.add(this.ks);
    return ret;
  }
コード例 #11
0
  private void testKeyFactory() throws Exception {
    KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", "SC");

    ECCurve curve =
        new ECCurve.Fp(
            new BigInteger(
                "883423532389192164791648750360308885314476597252960362792450860609699839"), // q
            new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a
            new BigInteger(
                "6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b

    ECParameterSpec ecSpec =
        new ECParameterSpec(
            curve,
            curve.decodePoint(
                Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G
            new BigInteger(
                "883423532389192164791648750360308884807550341691627752275345424702807307")); // n

    ConfigurableProvider config = (ConfigurableProvider) Security.getProvider("SC");

    config.setParameter(ConfigurableProvider.EC_IMPLICITLY_CA, ecSpec);

    g.initialize(null, new SecureRandom());

    KeyPair p = g.generateKeyPair();

    ECPrivateKey sKey = (ECPrivateKey) p.getPrivate();
    ECPublicKey vKey = (ECPublicKey) p.getPublic();

    KeyFactory fact = KeyFactory.getInstance("ECDSA", "SC");

    vKey = (ECPublicKey) fact.generatePublic(new ECPublicKeySpec(vKey.getQ(), null));
    sKey = (ECPrivateKey) fact.generatePrivate(new ECPrivateKeySpec(sKey.getD(), null));

    testECDSA(sKey, vKey);

    testBCParamsAndQ(sKey, vKey);
    testEC5Params(sKey, vKey);

    testEncoding(sKey, vKey);

    ECPublicKey vKey2 = (ECPublicKey) fact.generatePublic(new ECPublicKeySpec(vKey.getQ(), ecSpec));
    ECPrivateKey sKey2 =
        (ECPrivateKey) fact.generatePrivate(new ECPrivateKeySpec(sKey.getD(), ecSpec));

    if (!vKey.equals(vKey2) || vKey.hashCode() != vKey2.hashCode()) {
      fail("private equals/hashCode failed");
    }

    if (!sKey.equals(sKey2) || sKey.hashCode() != sKey2.hashCode()) {
      fail("private equals/hashCode failed");
    }

    // check we can get specs.
    fact.getKeySpec(vKey, java.security.spec.ECPublicKeySpec.class);

    fact.getKeySpec(sKey, java.security.spec.ECPrivateKeySpec.class);
  }
コード例 #12
0
 /**
  * Returns an instance of a <code>KeyStore</code> representing the specified type, from the named
  * provider.
  *
  * @param type the type of keystore to create.
  * @param provider the name of the provider to use.
  * @return a <code>KeyStore</code> repesenting the desired type.
  * @throws KeyStoreException if the designated type is not implemented by the given provider.
  * @throws NoSuchProviderException if the provider is not found.
  * @throws IllegalArgumentException if either <code>type</code> or <code>provider</code> is <code>
  *     null</code> or empty.
  */
 public static KeyStore getInstance(String type, String provider)
     throws KeyStoreException, NoSuchProviderException {
   if (provider == null) throw new IllegalArgumentException("provider MUST NOT be null");
   provider = provider.trim();
   if (provider.length() == 0) throw new IllegalArgumentException("provider MUST NOT be empty");
   Provider p = Security.getProvider(provider);
   if (p == null) throw new NoSuchProviderException(provider);
   return getInstance(type, p);
 }
コード例 #13
0
  private List<KeyStore> initDnieJava(
      final PasswordCallback pssCallBack, final Object parentComponent)
      throws AOKeyStoreManagerException, IOException {
    final Provider p;
    if (Security.getProvider(AOKeyStore.DNIEJAVA.getProviderName()) == null) {
      try {
        p =
            (Provider)
                Class.forName("es.gob.jmulticard.jse.provider.DnieProvider")
                    .newInstance(); //$NON-NLS-1$
        Security.addProvider(p);
      } catch (final Exception e) {
        throw new AOKeyStoreManagerException(
            "No se ha podido instanciar e instalar el proveedor 100% Java para DNIe de Afirma: "
                + e, //$NON-NLS-1$
            e);
      }
    }

    try {
      final Class<?> managerClass =
          Class.forName(
              "es.gob.jmulticard.ui.passwordcallback.PasswordCallbackManager"); //$NON-NLS-1$
      final Method setDialogOwnerFrameMethod =
          managerClass.getMethod("setDialogOwner", Component.class); // $NON-NLS-1$
      setDialogOwnerFrameMethod.invoke(null, parentComponent);
    } catch (final Exception e) {
      LOGGER.warning(
          "No se ha podido establecer el componente padre para los dialogos del almacen: "
              + e); //$NON-NLS-1$
    }

    // Inicializamos
    try {
      this.ks = KeyStore.getInstance(this.ksType.getProviderName());
    } catch (final Exception e) {
      throw new AOKeyStoreManagerException(
          "No se ha podido obtener el almacen DNIe 100% Java: " + e, e); // $NON-NLS-1$
    }

    LOGGER.info("Cargando KeyStore DNIe 100% Java"); // $NON-NLS-1$
    try {
      this.ks.load(null, pssCallBack == null ? null : pssCallBack.getPassword());
    } catch (final NoSuchAlgorithmException e) {
      throw new AOKeyStoreManagerException(
          "Error de algoritmo al obtener el almacen DNIe 100% Java: " + e, e); // $NON-NLS-1$
    } catch (final CertificateException e) {
      throw new AOKeyStoreManagerException(
          "Error de certificado al obtener el almacen DNIe 100% Java: " + e, e); // $NON-NLS-1$
    }

    final List<KeyStore> ret = new ArrayList<KeyStore>(1);
    ret.add(this.ks);
    return ret;
  }
コード例 #14
0
 public static final CertificateFactory getInstance(String type, String provider)
     throws CertificateException, NoSuchProviderException {
   if (provider == null || provider.isEmpty()) {
     throw new IllegalArgumentException("provider == null || provider.isEmpty()");
   }
   Provider impProvider = Security.getProvider(provider);
   if (impProvider != null) {
     return getInstance(type, impProvider);
   }
   throw new NoSuchProviderException(provider);
 }
コード例 #15
0
ファイル: MessageDigest.java プロジェクト: jshjs11/xi
 /**
  * Returns a new instance of {@code MessageDigest} that utilizes the specified algorithm from the
  * specified provider.
  *
  * @param algorithm the name of the algorithm to use
  * @param provider the name of the provider
  * @return a new instance of {@code MessageDigest} that utilizes the specified algorithm from the
  *     specified provider
  * @throws NoSuchAlgorithmException if the specified algorithm is not available
  * @throws NoSuchProviderException if the specified provider is not available
  * @throws NullPointerException if {@code algorithm} is {@code null}
  * @throws IllegalArgumentException if {@code provider == null || provider.isEmpty()}
  */
 public static MessageDigest getInstance(String algorithm, String provider)
     throws NoSuchAlgorithmException, NoSuchProviderException {
   if (provider == null || provider.isEmpty()) {
     throw new IllegalArgumentException();
   }
   Provider p = Security.getProvider(provider);
   if (p == null) {
     throw new NoSuchProviderException(provider);
   }
   return getInstance(algorithm, p);
 }
コード例 #16
0
 /**
  * Get an instance of a context for the specified protocol from the named provider.
  *
  * @param protocol The name of the protocol to get a context for.
  * @param provider The name of the provider to get the implementation from.
  * @return The new context.
  * @throws NoSuchAlgorithmException If the provider does not implement the given protocol.
  * @throws NoSuchProviderException If the named provider does not exist.
  * @throws IllegalArgumentException If <i>provider</i> is null.
  */
 public static final SSLContext getInstance(String protocol, String provider)
     throws NoSuchAlgorithmException, NoSuchProviderException {
   if (provider == null) {
     throw new IllegalArgumentException("null provider");
   }
   Provider p = Security.getProvider(provider);
   if (p == null) {
     throw new NoSuchProviderException(provider);
   }
   return getInstance(protocol, p);
 }
コード例 #17
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    java.util.Map<String, String[]> map = request.getParameterMap();
    String param = "";
    if (!map.isEmpty()) {
      param = map.get("foo")[0];
    }

    org.owasp.benchmark.helpers.ThingInterface thing =
        org.owasp.benchmark.helpers.ThingFactory.createThing();
    String bar = thing.doSomething(param);

    java.security.Provider[] provider = java.security.Security.getProviders();
    javax.crypto.Cipher c;

    try {
      if (provider.length > 1) {
        c =
            javax.crypto.Cipher.getInstance(
                "DES/CBC/PKCS5PADDING", java.security.Security.getProvider("SunJCE"));
      } else {
        c =
            javax.crypto.Cipher.getInstance(
                "DES/CBC/PKCS5PADDING", java.security.Security.getProvider("SunJCE"));
      }
    } catch (java.security.NoSuchAlgorithmException e) {
      System.out.println(
          "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case");
      throw new ServletException(e);
    } catch (javax.crypto.NoSuchPaddingException e) {
      System.out.println(
          "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case");
      throw new ServletException(e);
    }
    response
        .getWriter()
        .println(
            "Crypto Test javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) executed");
  }
コード例 #18
0
  public static Test suite() {
    TestSuite suite = new TestSuite("Cert Tests");

    if (Security.getProvider("BC") == null) {
      Security.addProvider(new BouncyCastleProvider());
    }

    suite.addTestSuite(AllTests.class);
    suite.addTest(ConverterTest.suite());

    return suite;
  }
コード例 #19
0
ファイル: PEMUtilities.java プロジェクト: JstnPwll/DroidText
  static byte[] crypt(
      boolean encrypt, String provider, byte[] bytes, char[] password, String dekAlgName, byte[] iv)
      throws IOException {
    Provider prov = null;
    if (provider != null) {
      prov = Security.getProvider(provider);
      if (prov == null) {
        throw new EncryptionException("cannot find provider: " + provider);
      }
    }

    return crypt(encrypt, prov, bytes, password, dekAlgName, iv);
  }
コード例 #20
0
  /**
   * Creates directory services, starts LDAP server and KDCServer
   *
   * @param managementClient
   * @param containerId
   * @throws Exception
   * @see
   *     org.jboss.as.arquillian.api.ServerSetupTask#setup(org.jboss.as.arquillian.container.ManagementClient,
   *     java.lang.String)
   */
  public void setup(ManagementClient managementClient, String containerId) throws Exception {
    try {
      if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
        Security.addProvider(new BouncyCastleProvider());
        removeBouncyCastle = true;
      }
    } catch (SecurityException ex) {
      LOGGER.warn("Cannot register BouncyCastleProvider", ex);
    }

    final String hostname = Utils.getHost(managementClient);
    createLdap1(managementClient, hostname);
  }
コード例 #21
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String param = "";
    java.util.Enumeration<String> headers = request.getHeaders("foo");
    if (headers.hasMoreElements()) {
      param = headers.nextElement(); // just grab first element
    }

    String bar = new Test().doSomething(param);

    java.security.Provider[] provider = java.security.Security.getProviders();
    javax.crypto.Cipher c;

    try {
      if (provider.length > 1) {
        c =
            javax.crypto.Cipher.getInstance(
                "DES/CBC/PKCS5PADDING", java.security.Security.getProvider("SunJCE"));
      } else {
        c =
            javax.crypto.Cipher.getInstance(
                "DES/CBC/PKCS5PADDING", java.security.Security.getProvider("SunJCE"));
      }
    } catch (java.security.NoSuchAlgorithmException e) {
      System.out.println(
          "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case");
      throw new ServletException(e);
    } catch (javax.crypto.NoSuchPaddingException e) {
      System.out.println(
          "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case");
      throw new ServletException(e);
    }
    response
        .getWriter()
        .println(
            "Crypto Test javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) executed");
  } // end doPost
コード例 #22
0
 public AxolotlService(Account account, XmppConnectionService connectionService) {
   if (Security.getProvider("BC") == null) {
     Security.addProvider(new BouncyCastleProvider());
   }
   this.mXmppConnectionService = connectionService;
   this.account = account;
   this.axolotlStore = new SQLiteAxolotlStore(this.account, this.mXmppConnectionService);
   this.deviceIds = new HashMap<>();
   this.messageCache = new HashMap<>();
   this.sessions = new SessionMap(mXmppConnectionService, axolotlStore, account);
   this.fetchStatusMap = new FetchStatusMap();
   this.executor = new SerialSingleThreadExecutor();
 }
コード例 #23
0
 @SuppressWarnings("unchecked")
 protected static boolean initProvider(String providerName, String className) {
   try {
     Provider provider = Security.getProvider(providerName);
     if (provider == null) {
       Class clazz = Class.forName(className);
       provider = (Provider) clazz.newInstance();
       Security.addProvider(provider);
     }
     return true;
   } catch (Throwable ignored) {
   }
   return false;
 }
コード例 #24
0
 /**
  * Returns a new instance of {@code Signature} that utilizes the specified algorithm from the
  * specified provider.
  *
  * @param algorithm the name of the algorithm to use.
  * @param provider the name of the provider.
  * @return a new instance of {@code Signature} that utilizes the specified algorithm from the
  *     specified provider.
  * @throws NoSuchAlgorithmException if the specified algorithm is not available.
  * @throws NoSuchProviderException if the specified provider is not available.
  * @throws NullPointerException if {@code algorithm} is {@code null}.
  * @throws IllegalArgumentException if {@code provider == null || provider.isEmpty()}
  */
 public static Signature getInstance(String algorithm, String provider)
     throws NoSuchAlgorithmException, NoSuchProviderException {
   if (algorithm == null) {
     throw new NullPointerException("algorithm == null");
   }
   if (provider == null || provider.isEmpty()) {
     throw new IllegalArgumentException();
   }
   Provider p = Security.getProvider(provider);
   if (p == null) {
     throw new NoSuchProviderException(provider);
   }
   return getSignature(algorithm, p);
 }
コード例 #25
0
  public MiscPEMGenerator(
      Object obj, String algorithm, char[] password, SecureRandom random, String provider)
      throws NoSuchProviderException {
    this.obj = obj;
    this.algorithm = algorithm;
    this.password = password;
    this.random = random;

    if (provider != null) {
      this.provider = Security.getProvider(provider);
      if (this.provider == null) {
        throw new NoSuchProviderException("cannot find provider: " + provider);
      }
    }
  }
コード例 #26
0
  /** Erstellt ein neues {@link AESCryptoCodecBC} Object. */
  public AESCryptoCodecBC() {
    super();

    if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
      Security.addProvider(new BouncyCastleProvider());
    }

    setInitVector(Arrays.copyOf(DEFAULT_INIT_VECTOR, 64));

    setProviderKey(BouncyCastleProvider.PROVIDER_NAME);
    setAlgorythmKey("PBEWITHSHA256AND256BITAES-CBC-BC");

    setProviderCipher(BouncyCastleProvider.PROVIDER_NAME);
    setAlgorythmCipher("PBEWITHSHA256AND256BITAES-CBC-BC");
  }
コード例 #27
0
ファイル: CipherUtil.java プロジェクト: hbklove8/syncany
  public static synchronized void init() {
    if (!initialized) {
      logger.log(Level.INFO, "Initializing crypto settings and security provider ...");

      // Bouncy Castle
      if (Security.getProvider(PROVIDER) == null) {
        Security.addProvider(new BouncyCastleProvider());
      }

      // Unlimited strength
      try {
        unlimitedStrengthEnabled = Cipher.getMaxAllowedKeyLength("AES") > 128;
      } catch (Exception e) {
        unlimitedStrengthEnabled = false;
      }

      initialized = true;
    }
  }
コード例 #28
0
 static {
   boolean loaded;
   if (Security.getProvider("BC") == null) {
     try {
       Class<?> cls = Class.forName("org.bouncycastle.jce.provider.BouncyCastleProvider");
       Constructor<?> con = cls.getConstructor(new Class[0]);
       Provider bc = (Provider) con.newInstance(new Object[0]);
       Security.addProvider(bc);
       log("Added BC provider");
       loaded = true;
     } catch (Exception e) {
       log("Unable to add BC provider", e);
       loaded = false;
     }
   } else {
     log("BC provider already loaded");
     loaded = true;
   }
   BC_AVAILABLE = loaded;
 }
コード例 #29
0
ファイル: Tor.java プロジェクト: happysir/TorProxy
  private void init_phase1(boolean noLocalFileSystemAccess, boolean fastStartup)
      throws IOException {
    // install BC, if not already done
    if (Security.getProvider("BC") == null) {
      Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
      // Security.insertProviderAt(new org.bouncycastle.jce.provider.BouncyCastleProvider(),2);
    }

    // logger and config
    Logger.logGeneral(
        Logger.INFO,
        "TorJava is starting up. Please don't use this implementation for strong anonymity!");
    // create identity
    privateKeyHandler = new PrivateKeyHandler(fastStartup);
    // determine end of startup-Phase
    startupPhaseWithoutConnects =
        System.currentTimeMillis() + TorConfig.startupDelaySeconds * 1000L;
    // init event-handler
    eventHandler = new Vector<TorEventHandler>();
  }
コード例 #30
0
  private void testBasicThreadLocal() throws Exception {
    KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", "SC");

    EllipticCurve curve =
        new EllipticCurve(
            new ECFieldFp(
                new BigInteger(
                    "883423532389192164791648750360308885314476597252960362792450860609699839")), // q
            new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a
            new BigInteger(
                "6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b

    java.security.spec.ECParameterSpec ecSpec =
        new java.security.spec.ECParameterSpec(
            curve,
            ECPointUtil.decodePoint(
                curve,
                Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G
            new BigInteger(
                "883423532389192164791648750360308884807550341691627752275345424702807307"), // n
            1); // h

    ConfigurableProvider config = (ConfigurableProvider) Security.getProvider("SC");

    config.setParameter(ConfigurableProvider.THREAD_LOCAL_EC_IMPLICITLY_CA, ecSpec);

    g.initialize(null, new SecureRandom());

    KeyPair p = g.generateKeyPair();

    ECPrivateKey sKey = (ECPrivateKey) p.getPrivate();
    ECPublicKey vKey = (ECPublicKey) p.getPublic();

    testECDSA(sKey, vKey);

    testBCParamsAndQ(sKey, vKey);
    testEC5Params(sKey, vKey);

    testEncoding(sKey, vKey);
  }