Example usage for org.bouncycastle.jce.provider BouncyCastleProvider BouncyCastleProvider

List of usage examples for org.bouncycastle.jce.provider BouncyCastleProvider BouncyCastleProvider

Introduction

In this page you can find the example usage for org.bouncycastle.jce.provider BouncyCastleProvider BouncyCastleProvider.

Prototype

public BouncyCastleProvider() 

Source Link

Document

Construct a new provider.

Usage

From source file:com.arrow.acn.client.utils.SslUtil.java

License:Open Source License

public static SSLSocketFactory getSocketFactory(final String caCertContent, final String certContent,
        final String keyContent) throws Exception {
    Security.addProvider(new BouncyCastleProvider());

    // load CA certificate
    PEMReader reader = new PEMReader(new StringReader(caCertContent));
    X509Certificate caCert = (X509Certificate) reader.readObject();
    reader.close();/*from   w  ww  . j  av a  2 s .  com*/

    // load client certificate
    reader = new PEMReader(new StringReader(certContent));
    X509Certificate cert = (X509Certificate) reader.readObject();
    reader.close();

    // load client private key
    reader = new PEMReader(new StringReader(keyContent));
    KeyPair key = (KeyPair) reader.readObject();
    reader.close();

    // CA certificate is used to authenticate server
    KeyStore caKs = KeyStore.getInstance(KeyStore.getDefaultType());
    caKs.load(null, null);
    caKs.setCertificateEntry("ca-certificate", caCert);
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(caKs);

    // client key and certificates are sent to server so it can authenticate
    // us
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(null, null);
    ks.setCertificateEntry("certificate", cert);
    ks.setKeyEntry("private-key", key.getPrivate(), new char[0], new Certificate[] { cert });
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(ks, new char[0]);

    // finally, create SSL socket factory
    SSLContext context = SSLContext.getInstance("TLSv1.2");
    context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

    return context.getSocketFactory();
}

From source file:com.aspose.showcase.qrcodegen.web.api.util.StringEncryptor.java

License:Open Source License

public static String encrypt(String data, String password) throws Exception {

    Security.addProvider(new BouncyCastleProvider());
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");

    final Random r = new SecureRandom();
    byte[] salt = new byte[SALT_SIZE];
    r.nextBytes(salt);/*from   w ww.j a v  a2 s . co  m*/

    SecretKeyFactory fact = SecretKeyFactory.getInstance("PBEWITHMD5AND128BITAES-CBC-OPENSSL", "BC");

    cipher.init(Cipher.ENCRYPT_MODE,
            fact.generateSecret(new PBEKeySpec(password.toCharArray(), salt, PBE_KEY_SALE_SIZE)));

    byte[] encVal = cipher.doFinal(data.getBytes());

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    // writing encrypted data along with the salt in the format readable by
    // open ssl api
    bos.write("Salted__".getBytes());
    bos.write(salt);
    bos.write(encVal);
    String encryptedValue = new String(Base64.encode(bos.toByteArray()));
    bos.close();

    return encryptedValue;

}

From source file:com.aspose.showcase.qrcodegen.web.api.util.StringEncryptor.java

License:Open Source License

public static String decrypt(String encryptedData, String password) throws Exception {

    Security.addProvider(new BouncyCastleProvider());

    byte[] encrypted = Base64.decode(encryptedData);

    Cipher cipher0 = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");

    // Openssl puts SALTED__ then the 8 byte salt at the start of the file.
    // We simply copy it out.
    byte[] salt = new byte[SALT_SIZE];
    System.arraycopy(encrypted, SALT_SIZE, salt, 0, SALT_SIZE);

    SecretKeyFactory fact = SecretKeyFactory.getInstance("PBEWITHMD5AND128BITAES-CBC-OPENSSL", "BC");
    cipher0.init(Cipher.DECRYPT_MODE,
            fact.generateSecret(new PBEKeySpec(password.toCharArray(), salt, PBE_KEY_SALE_SIZE)));

    // Decrypt the rest of the byte array (after stripping off the salt)
    byte[] decValue = cipher0.doFinal(encrypted, SALT_STRIP_LENGTH, encrypted.length - SALT_STRIP_LENGTH);

    return new String(decValue);
}

From source file:com.axelor.apps.account.ebics.certificate.CertificateManager.java

License:Open Source License

/**
 * Creates the certificates for the user
 * @throws GeneralSecurityException/* w  ww .j  av  a  2  s.c  o m*/
 * @throws IOException
 */
public void create() throws GeneralSecurityException, IOException {

    Calendar calendar;

    calendar = Calendar.getInstance();
    calendar.add(Calendar.DAY_OF_YEAR, X509Constants.DEFAULT_DURATION);

    org.apache.xml.security.Init.init();
    java.security.Security.addProvider(new BouncyCastleProvider());

    createA005Certificate(new Date(calendar.getTimeInMillis()));
    createX002Certificate(new Date(calendar.getTimeInMillis()));
    createE002Certificate(new Date(calendar.getTimeInMillis()));
    setUserCertificates();
}

From source file:com.axelor.apps.account.ebics.certificate.CertificateManager.java

License:Open Source License

/**
 * Writes a the generated certificates into a PKCS12 key store.
 * @param password the key store password
 * @param fos the output stream//from   w  w w  .j a  v a2  s.c  o  m
 * @throws GeneralSecurityException
 * @throws IOException
 */
public void writePKCS12Certificate(char[] password, OutputStream fos)
        throws GeneralSecurityException, IOException {
    KeyStore keystore;

    keystore = KeyStore.getInstance("PKCS12", new BouncyCastleProvider());
    keystore.load(null, null);
    keystore.setKeyEntry(user.getUserId() + "-A005", a005PrivateKey, password,
            new X509Certificate[] { a005Certificate });
    keystore.setKeyEntry(user.getUserId() + "-X002", x002PrivateKey, password,
            new X509Certificate[] { x002Certificate });
    keystore.setKeyEntry(user.getUserId() + "-E002", e002PrivateKey, password,
            new X509Certificate[] { e002Certificate });
    keystore.store(fos, password);
}

From source file:com.bekwam.resignator.ResignatorApp.java

License:Apache License

@Override
public void start(Stage primaryStage) throws Exception {

    if (logger.isDebugEnabled()) {
        logger.debug("[START] starting app");
    }/* w  w w .j ava2s  .c om*/

    Platform.setImplicitExit(false);

    primaryStage.setTitle("Resignator");

    primaryStage.getIcons().addAll(new Image("/images/Logo16.png", true),
            new Image("/images/Logo32.png", true));

    Security.addProvider(new BouncyCastleProvider());

    //
    // Initiaize Google Guice
    //
    Injector injector = Guice.createInjector(new ResignatorModule());

    ResignatorAppMainViewController mv = injector.getInstance(ResignatorAppMainViewController.class);

    try {
        mv.show(); // ignoring the primaryStage
    } catch (Exception exc) {
        String msg = "Error launching ResignatorApp";
        logger.error(msg, exc);
        Alert alert = new Alert(Alert.AlertType.ERROR, msg);
        alert.showAndWait();
    }
}

From source file:com.bekwam.resignator.util.CryptUtilsTest.java

License:Apache License

@BeforeClass
public static void setup() {
    Security.addProvider(new BouncyCastleProvider());
}

From source file:com.bitsofproof.btc1k.server.Btc1kApplication.java

License:Apache License

public static void main(String[] args) throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    new Btc1kApplication().run(args);
}

From source file:com.bitsofproof.example.Simple.java

License:Apache License

public static void main(String[] args) {
    Security.addProvider(new BouncyCastleProvider());

    final CommandLineParser parser = new GnuParser();
    final Options gnuOptions = new Options();
    gnuOptions.addOption("h", "help", false, "I can't help you yet");
    gnuOptions.addOption("s", "server", true, "Server URL");
    gnuOptions.addOption("u", "user", true, "User");
    gnuOptions.addOption("p", "password", true, "Password");

    System.out.println("BOP Bitcoin Server Simple Client 3.5.0 (c) 2013-2014 bits of proof zrt.");
    CommandLine cl = null;/*from w  w w  .ja  va  2s. com*/
    String url = null;
    String user = null;
    String password = null;
    try {
        cl = parser.parse(gnuOptions, args);
        url = cl.getOptionValue('s');
        user = cl.getOptionValue('u');
        password = cl.getOptionValue('p');
    } catch (org.apache.commons.cli.ParseException e) {
        e.printStackTrace();
        System.exit(1);
    }
    if (url == null || user == null || password == null) {
        System.err.println("Need -s server -u user -p password");
        System.exit(1);
    }

    BCSAPI api = getServer(url, user, password);
    try {
        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
        long start = System.currentTimeMillis();
        api.ping(start);
        System.out.println("Server round trip " + (System.currentTimeMillis() - start) + "ms");
        api.addAlertListener(new AlertListener() {
            @Override
            public void alert(String s, int severity) {
                System.err.println("ALERT: " + s);
            }
        });
        System.out.println("Talking to " + (api.isProduction() ? "PRODUCTION" : "test") + " server");
        ConfirmationManager confirmationManager = new ConfirmationManager();
        confirmationManager.init(api, 144);
        System.out.printf("Please enter wallet name: ");
        String wallet = input.readLine();
        SimpleFileWallet w = new SimpleFileWallet(wallet + ".wallet");
        TransactionFactory am = null;
        if (!w.exists()) {
            System.out.printf("Enter passphrase: ");
            String passphrase = input.readLine();
            System.out.printf("Enter master (empty for new): ");
            String master = input.readLine();
            if (master.equals("")) {
                w.init(passphrase);
                w.unlock(passphrase);
                System.out.printf("First account: ");
                String account = input.readLine();
                am = w.createAccountManager(account);
                w.lock();
                w.persist();
            } else {
                StringTokenizer tokenizer = new StringTokenizer(master, "@");
                String key = tokenizer.nextToken();
                long since = 0;
                if (tokenizer.hasMoreElements()) {
                    since = Long.parseLong(tokenizer.nextToken()) * 1000;
                }
                w.init(passphrase, ExtendedKey.parse(key), true, since);
                w.unlock(passphrase);
                System.out.printf("First account: ");
                String account = input.readLine();
                am = w.createAccountManager(account);
                w.lock();
                w.persist();
                w.sync(api);
            }
        } else {
            w = SimpleFileWallet.read(wallet + ".wallet");
            w.sync(api);
            List<String> names = w.getAccountNames();
            System.out.println("Accounts:");
            System.out.println("---------");
            String first = null;
            for (String name : names) {
                System.out.println(name);
                if (first == null) {
                    first = name;
                }
            }
            System.out.println("---------");
            am = w.getAccountManager(first);
            System.out.println("Using account " + first);
        }
        confirmationManager.addAccount(am);
        api.registerTransactionListener(am);

        while (true) {
            printMenu();
            String answer = input.readLine();
            System.out.printf("\n");
            if (answer.equals("1")) {
                System.out.printf("The balance is: " + printBit(am.getBalance()) + "\n");
                System.out.printf("     confirmed: " + printBit(am.getConfirmed()) + "\n");
                System.out.printf("    receiveing: " + printBit(am.getReceiving()) + "\n");
                System.out.printf("        change: " + printBit(am.getChange()) + "\n");
                System.out.printf("(      sending: " + printBit(am.getSending()) + ")\n");
            } else if (answer.equals("2")) {
                for (Address a : am.getAddresses()) {
                    System.out.printf(a + "\n");
                }
            } else if (answer.equals("3")) {
                ExtendedKeyAccountManager im = (ExtendedKeyAccountManager) am;
                System.out.printf(
                        im.getMaster().serialize(api.isProduction()) + "@" + im.getCreated() / 1000 + "\n");
            } else if (answer.equals("4")) {
                System.out.printf("Enter passphrase: ");
                String passphrase = input.readLine();
                w.unlock(passphrase);
                ExtendedKeyAccountManager im = (ExtendedKeyAccountManager) am;
                System.out.printf(
                        im.getMaster().serialize(api.isProduction()) + "@" + im.getCreated() / 1000 + "\n");
                w.lock();
            } else if (answer.equals("5")) {
                System.out.printf("Enter passphrase: ");
                String passphrase = input.readLine();
                w.unlock(passphrase);
                System.out.printf("Number of recipients");
                Integer nr = Integer.valueOf(input.readLine());
                Transaction spend;
                if (nr.intValue() == 1) {
                    System.out.printf("Receiver address: ");
                    String address = input.readLine();
                    System.out.printf("amount (Bit): ");
                    long amount = parseBit(input.readLine());
                    spend = am.pay(Address.fromSatoshiStyle(address), amount);
                    System.out.println("About to send " + printBit(amount) + " to " + address);
                } else {
                    List<Address> addresses = new ArrayList<>();
                    List<Long> amounts = new ArrayList<>();
                    long total = 0;
                    for (int i = 0; i < nr; ++i) {
                        System.out.printf("Receiver address: ");
                        String address = input.readLine();
                        addresses.add(Address.fromSatoshiStyle(address));
                        System.out.printf("amount (Bit): ");
                        long amount = parseBit(input.readLine());
                        amounts.add(amount);
                        total += amount;
                    }
                    spend = am.pay(addresses, amounts);
                    System.out.println("About to send " + printBit(total));
                }
                System.out.println("inputs");
                for (TransactionInput in : spend.getInputs()) {
                    System.out.println(in.getSourceHash() + " " + in.getIx());
                }
                System.out.println("outputs");
                for (TransactionOutput out : spend.getOutputs()) {
                    System.out.println(out.getOutputAddress() + " " + printBit(out.getValue()));
                }
                w.lock();
                System.out.printf("Type yes to go: ");
                if (input.readLine().equals("yes")) {
                    api.sendTransaction(spend);
                    System.out.printf("Sent transaction: " + spend.getHash());
                } else {
                    System.out.printf("Nothing happened.");
                }
            } else if (answer.equals("6")) {
                System.out.printf("Address: ");
                Set<Address> match = new HashSet<Address>();
                match.add(Address.fromSatoshiStyle(input.readLine()));
                api.scanTransactionsForAddresses(match, 0, new TransactionListener() {
                    @Override
                    public boolean process(Transaction t) {
                        System.out.printf("Found transaction: " + t.getHash() + "\n");
                        return true;
                    }
                });
            } else if (answer.equals("7")) {
                System.out.printf("Public key: ");
                ExtendedKey ek = ExtendedKey.parse(input.readLine());
                api.scanTransactions(ek, 0, 10, 0, new TransactionListener() {
                    @Override
                    public boolean process(Transaction t) {
                        System.out.printf("Found transaction: " + t.getHash() + "\n");
                        return true;
                    }
                });
            } else if (answer.equals("a")) {
                System.out.printf("Enter account name: ");
                String account = input.readLine();
                am = w.getAccountManager(account);
                api.registerTransactionListener(am);
                confirmationManager.addAccount(am);
            } else if (answer.equals("c")) {
                System.out.printf("Enter account name: ");
                String account = input.readLine();
                System.out.printf("Enter passphrase: ");
                String passphrase = input.readLine();
                w.unlock(passphrase);
                am = w.createAccountManager(account);
                System.out.println("using account: " + account);
                w.lock();
                w.persist();
                api.registerTransactionListener(am);
                confirmationManager.addAccount(am);
            } else if (answer.equals("m")) {
                System.out.printf("Enter passphrase: ");
                String passphrase = input.readLine();
                w.unlock(passphrase);
                System.out.println(w.getMaster().serialize(api.isProduction()));
                System.out.println(w.getMaster().getReadOnly().serialize(true));
                w.lock();
            } else if (answer.equals("s")) {
                System.out.printf("Enter private key: ");
                String key = input.readLine();
                ECKeyPair k = ECKeyPair.parseWIF(key);
                KeyListAccountManager alm = new KeyListAccountManager();
                alm.addKey(k);
                alm.syncHistory(api);
                Address a = am.getNextReceiverAddress();
                Transaction t = alm.pay(a, alm.getBalance(), PaymentOptions.receiverPaysFee);
                System.out.println("About to sweep " + printBit(alm.getBalance()) + " to " + a);
                System.out.println("inputs");
                for (TransactionInput in : t.getInputs()) {
                    System.out.println(in.getSourceHash() + " " + in.getIx());
                }
                System.out.println("outputs");
                for (TransactionOutput out : t.getOutputs()) {
                    System.out.println(out.getOutputAddress() + " " + printBit(out.getValue()));
                }
                System.out.printf("Type yes to go: ");
                if (input.readLine().equals("yes")) {
                    api.sendTransaction(t);
                    System.out.printf("Sent transaction: " + t.getHash());
                } else {
                    System.out.printf("Nothing happened.");
                }
            } else {
                System.exit(0);
            }
        }
    } catch (Exception e) {
        System.err.println("Something went wrong");
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:com.bitsofproof.supernode.main.Main.java

License:Apache License

public static void main(String[] args) throws Exception {
    log.info("bitsofproof supernode (c) 2013 bits of proof zrt.");
    Security.addProvider(new BouncyCastleProvider());
    log.trace("Spring context setup");

    if (args.length == 0) {
        System.err.println(//from w w w  . jav a2s .  c o m
                "Usage: java com.bitsofproof.main.Main profile [profile...] -- [args...] [options...]");
        return;
    }

    try {
        GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
        List<String> a = new ArrayList<String>();
        boolean profiles = true;
        for (String s : args) {
            if (s.equals("--")) {
                profiles = false;
            } else {
                if (profiles) {
                    log.info("Loading profile: " + s);
                    ctx.getEnvironment().addActiveProfile(s);
                } else {
                    a.add(s);
                }
            }
        }
        ctx.load("classpath:context/server.xml");
        ctx.load("classpath:context/*-profile.xml");
        ctx.refresh();
        ctx.getBean(App.class).start(a.toArray(new String[0]));
    } catch (Exception e) {
        log.error("Error setting up spring context", e);
    }
}