Ejemplo n.º 1
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();
  }
Ejemplo n.º 2
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
 static {
   for (Provider provider : Security.getProviders()) {
     if (provider.getName().startsWith("SunPKCS11")) {
       Security.removeProvider(provider.getName());
     }
   }
 }
Ejemplo n.º 4
0
 private static void initSystemProperties() {
   // currently we support IPv4 only
   System.setProperty("java.net.preferIPv4Stack", "true");
   // disable DNS caches
   Security.setProperty("networkaddress.cache.ttl", "0");
   Security.setProperty("networkaddress.cache.negative.ttl", "0");
 }
Ejemplo n.º 5
0
  /**
   * 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;
  }
Ejemplo n.º 6
0
  private static Properties getImapMailProperties(Account account) {
    Properties props = new Properties();

    if (account.getReceiveProtocolType().contains("gmail")) {
      props.put("mail.imap.host", "imap.gmail.com");
      props.put("mail.imap.port", "143");
      props.put("mail.imap.auth", "true");
      props.put("mail.store.protocol", "imap");
      props.put("mail.imap.starttls.enable", "true");
      props.put("mail.imap.socketFactory.port", "993");
      props.put("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
      props.put("mail.iamp.socketFactory.fallback", "false");
    } else {

      props.setProperty("mail.imap.port", account.getReceivePort());
      props.setProperty("mail.imap.connectiontimeout", "30000");
      if ("ssl".equals(account.getReceiveTs())) {
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        props.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.setProperty("mail.imap.socketFactory.fallback", "false");
        props.setProperty("mail.imap.socketFactory.port", account.getReceivePort());
      } else if ("tls".equals(account.getReceiveTs())) {
        props.setProperty("mail.imap.starttls.enable", "true");
        java.security.Security.setProperty(
            "ssl.SocketFactory.provider", "com.archermind.txtbl.mail.DummySSLSocketFactory");
      }
    }

    return props;
  }
 /**
  * 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();
 }
Ejemplo n.º 8
0
 /**
  * Returns SSLContext with TESTED_SECURITY_PROTOCOL protocol and sets up keys.
  *
  * @return - SSLContext with a protocol specified by TESTED_SECURITY_PROTOCOL.
  */
 public static SSLContext getContext() {
   try {
     java.security.Security.setProperty("jdk.tls.disabledAlgorithms", "");
     java.security.Security.setProperty("jdk.certpath.disabledAlgorithms", "");
     KeyStore ks = KeyStore.getInstance("JKS");
     KeyStore ts = KeyStore.getInstance("JKS");
     char[] passphrase = PASSWD.toCharArray();
     try (FileInputStream keyFileStream = new FileInputStream(KEY_FILE_NAME)) {
       ks.load(keyFileStream, passphrase);
     }
     try (FileInputStream trustFileStream = new FileInputStream(TRUST_FILE_NAME)) {
       ts.load(trustFileStream, passphrase);
     }
     KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
     kmf.init(ks, passphrase);
     TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
     tmf.init(ts);
     SSLContext sslCtx = SSLContext.getInstance(TESTED_SECURITY_PROTOCOL);
     sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
     return sslCtx;
   } catch (KeyStoreException
       | IOException
       | NoSuchAlgorithmException
       | CertificateException
       | UnrecoverableKeyException
       | KeyManagementException ex) {
     throw new Error("Unexpected exception", ex);
   }
 }
  /**
   * 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();
  }
Ejemplo n.º 10
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");
  }
  @Override
  public void contextInitialized(ServletContextEvent sce) {
    BouncyCastleProvider bouncyCastleProvider = new BouncyCastleProvider();

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

    Security.addProvider(bouncyCastleProvider);
  }
Ejemplo n.º 12
0
  public static void main(String[] args) throws Exception {
    java.security.Security.addProvider(new cryptix.jce.provider.CryptixCrypto());
    java.security.Security.addProvider(new cryptix.openpgp.provider.CryptixOpenPGP());

    readKeyrings();
    decodeKeyRings();

    writeMsg();
  }
Ejemplo n.º 13
0
  public void initialise() throws InitialisationException {
    try {
      java.security.Security.addProvider(new cryptix.jce.provider.CryptixCrypto());
      java.security.Security.addProvider(new cryptix.openpgp.provider.CryptixOpenPGP());

      factory = new PGPSecurityContextFactory();
    } catch (Exception e) {
      throw new InitialisationException(CoreMessages.failedToCreate("PGPProvider"), e, this);
    }
  }
Ejemplo n.º 14
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;
  }
Ejemplo n.º 15
0
 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();
 }
Ejemplo n.º 16
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;
  }
Ejemplo n.º 17
0
 @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());
     }
   }
 }
Ejemplo n.º 18
0
 static {
   try {
     Security.addProvider((Provider) Class.forName(DEFAULT_JCE).newInstance());
   } catch (Exception e) {
     log.info(e);
     try {
       Security.addProvider((Provider) Class.forName(IBM_JCE).newInstance());
     } catch (Exception ex) {
       log.info(ex);
     }
   }
 }
Ejemplo n.º 19
0
  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");
    }
  }
Ejemplo n.º 20
0
 public static void init() {
   System.setProperty(
       WMStaticConstants.HTTP_PROXY_HOST,
       StaticResourceFactory.getProperty(
           WMStaticConstants.WEALTH_MGMT_MODULE_NAME, WMStaticConstants.HTTP_PROXY_HOST));
   System.setProperty(
       WMStaticConstants.HTTP_PROXY_PORT,
       StaticResourceFactory.getProperty(
           WMStaticConstants.WEALTH_MGMT_MODULE_NAME, WMStaticConstants.HTTP_PROXY_PORT));
   Security.setProperty("ssl.SocketFactory.provider", "com.ibm.jsse2.SSLSocketFactoryImpl");
   Security.setProperty(
       "ssl.ServerSocketFactory.provider", "com.ibm.jsse2.SSLServerSocketFactoryImpl");
 }
  /**
   * 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);
  }
Ejemplo n.º 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();
 }
Ejemplo n.º 23
0
  public void initialise() throws InitialisationException {
    try {
      java.security.Security.addProvider(new cryptix.jce.provider.CryptixCrypto());
      java.security.Security.addProvider(new cryptix.openpgp.provider.CryptixOpenPGP());

      principalsKeyBundleMap = new HashMap();

      readPublicKeyRing();
      readPrivateKeyBundle();
    } catch (Exception e) {
      logger.error("errore in inizializzazione:" + e.getMessage(), e);
      throw new InitialisationException(CoreMessages.failedToCreate("PGPKeyRingImpl"), e, this);
    }
  }
Ejemplo n.º 24
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;
 }
Ejemplo n.º 25
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");
  }
Ejemplo n.º 26
0
 private static Properties getPop3MailProperties(Account account) {
   Properties props = new Properties();
   props.setProperty("mail.pop3.port", account.getReceivePort());
   props.setProperty("mail.pop3.connectiontimeout", "30000");
   if ("ssl".equals(account.getReceiveTs())) {
     Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
     props.setProperty("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
     props.setProperty("mail.pop3.socketFactory.fallback", "false");
     props.setProperty("mail.pop3.socketFactory.port", account.getReceivePort());
   } else if ("tls".equals(account.getReceiveTs())) {
     props.setProperty("mail.pop3.starttls.enable", "true");
     java.security.Security.setProperty(
         "ssl.SocketFactory.provider", "com.archermind.txtbl.mail.DummySSLSocketFactory");
   }
   return props;
 }
Ejemplo n.º 27
0
  public void send(String mailto, String subject, String textMessage, String contentType)
      throws FileNotFoundException, MessagingException {
    Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
    Properties props = new Properties();
    props.put("mail.smtp.user", smtpUsername);
    props.put("mail.smtp.host", smtpHost);
    props.put("mail.smtp.port", smtpPort);
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtps.auth", "true");
    props.put("mail.smtp.debug", "true");
    props.put("mail.smtp.socketFactory.port", smtpPort);
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.socketFactory.fallback", "false");
    props.put("mail.smtp.ssl", "true");

    Authenticator auth = new SMTPAuthenticator();
    Session smtpSession = Session.getInstance(props, auth);
    smtpSession.setDebug(true);

    Message message = new MimeMessage(smtpSession);
    InternetAddress[] address = {new InternetAddress(mailto)};
    message.setRecipients(Message.RecipientType.TO, address);
    message.setSubject(subject);
    message.setSentDate(new Date());
    message.setContent(textMessage, contentType);

    Transport tr = smtpSession.getTransport("smtp");
    tr.connect(smtpHost, smtpUsername, smtpPassword);
    tr.sendMessage(message, message.getAllRecipients());
    tr.close();
  }
Ejemplo n.º 28
0
  static {
    String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
    if (algorithm == null) {
      algorithm = "SunX509";
    }

    SSLContext serverContext;
    SSLContext clientContext;
    try {
      KeyStore ks = KeyStore.getInstance("JKS");
      ks.load(BogusKeyStore.asInputStream(), BogusKeyStore.getKeyStorePassword());

      // Set up key manager factory to use our key store
      KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
      kmf.init(ks, BogusKeyStore.getCertificatePassword());

      // Initialize the SSLContext to work with our key managers.
      serverContext = SSLContext.getInstance(PROTOCOL);
      serverContext.init(kmf.getKeyManagers(), null, null);
    } catch (Exception e) {
      throw new Error("Failed to initialize the server-side SSLContext", e);
    }

    try {
      clientContext = SSLContext.getInstance(PROTOCOL);
      clientContext.init(null, BogusTrustManagerFactory.getTrustManagers(), null);
    } catch (Exception e) {
      throw new Error("Failed to initialize the client-side SSLContext", e);
    }

    SERVER_CONTEXT = serverContext;
    CLIENT_CONTEXT = clientContext;
  }
Ejemplo n.º 29
0
  private static void bcDES() throws Exception {
    Security.addProvider(new BouncyCastleProvider());

    // Key convert
    DESKeySpec desKeySpec = new DESKeySpec(bytesKey);
    SecretKeyFactory factory = SecretKeyFactory.getInstance("DES", "BC");
    SecretKey desKey = factory.generateSecret(desKeySpec);

    Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, desKey);

    System.out.println("BC" + cipher.getProvider());

    byte[] result = cipher.doFinal("ABC".getBytes());
    String hexResult = Hex.encodeHexString(result);
    System.out.println(hexResult);

    cipher.init(Cipher.DECRYPT_MODE, desKey);
    result =
        cipher.doFinal(
            Hex.decodeHex(hexResult.toCharArray())
            // result
            );
    System.out.println(new String(result));
  }
Ejemplo n.º 30
0
  /**
   * Decrypt a partialy file encrypted. Generate a signle file, totally decrypted.
   *
   * @param password String password used to crypt the file
   * @param output String path to the output file
   * @throws FileNotFoundException
   * @throws IOException
   * @throws GeneralSecurityException
   */
  public void decrypt(String password, String output)
      throws FileNotFoundException, IOException, GeneralSecurityException {
    this.prefix = FileUtility.unaggregate(this.file, this.marker);

    // use the API
    Security.addProvider(new BouncyCastleProvider());

    // create a new crypter
    FileCrypter crypter = new FileCrypter();

    // get key to be used from the password
    SecretKeySpec key = Password.getKey(password);

    // decrypt the second file (which is supposed to be crypted)
    crypter.decryptFile(
        key,
        this.file + FileUtility.extension_crypt,
        FileUtility.tmp + this.prefix + "-2" + FileUtility.extension_tmp);

    // recompose the file with an encrypted part in one single file
    FileUtility.recompose(this.prefix, output);

    // clean temporary files
    FileUtility.clean();
  }