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.streamsets.pipeline.stage.processor.crypto.FieldEncrypter.java

License:Apache License

public List<ConfigIssue> init(List<ConfigIssue> issues) {
    if (Security.getProvider("BC") == null) {
        Security.addProvider(new BouncyCastleProvider());
    }/*from   ww  w . java 2 s .  c o  m*/

    if (conf.isDataKeyCaching() && !conf.getCipher().isSafeToCache()) {
        issues.add(getContext().createConfigIssue(ProcessorEncryptGroups.PROVIDER.name(), "conf.dataKeyCaching",
                CRYPTO_06));
    }

    encryptionProvider = createProvider(issues);

    if (!issues.isEmpty()) {
        return issues;
    }

    issues.addAll(encryptionProvider.init(getContext())); // NOSONAR false positive

    return issues;
}

From source file:com.swisscom.ais.itext.Connect.java

License:Open Source License

/**
 * Constructor to set relevant parameters and add security provider
 *
 * @param url        URL of the server where to connect
 * @param privateKey Private key of the user
 * @param serverCert Certificate of the server where to connect
 * @param clientCert Certificate to connect to the server and it should trust
 * @param timeout    Time for connection timeout in milli seconds
 * @param debug      If debug is set to true debug information will be print out. Otherwise it will not print debug information.
 *//*from  ww w .  j  a va  2 s.c  o m*/
public Connect(@Nonnull String url, @Nonnull String privateKey, @Nonnull String serverCert,
        @Nonnull String clientCert, int timeout, boolean debug) {
    this._url = url;
    this._privateKey = privateKey;
    this._serverCert = serverCert;
    this._clientCert = clientCert;
    this._timeout = timeout;
    _debugMode = debug;

    Security.addProvider(new BouncyCastleProvider());
}

From source file:com.telefonica.euro_iaas.sdc.util.RSASignerImpl.java

License:Apache License

/**
 * {@inheritDoc}//  w  ww . j a  v  a2 s.  c  o  m
 */

public String sign(String message, File pemFile) {
    try {
        Security.addProvider(new BouncyCastleProvider());
        PrivateKey privateKey = readKeyPair(pemFile, "".toCharArray()).getPrivate();

        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);

        byte[] digest = cipher.doFinal(message.getBytes());
        return Base64.encodeBase64String(digest);
    } catch (IOException e) {
        throw new SdcRuntimeException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new SdcRuntimeException(e);
    } catch (InvalidKeyException e) {
        throw new SdcRuntimeException(e);
    } catch (NoSuchPaddingException e) {
        throw new SdcRuntimeException(e);
    } catch (IllegalBlockSizeException e) {
        throw new SdcRuntimeException(e);
    } catch (BadPaddingException e) {
        throw new SdcRuntimeException(e);
    }
}

From source file:com.telefonica.euro_iaas.sdc.util.RSASignerImpl.java

License:Apache License

/**
 * {@inheritDoc}//  ww  w.j a v  a2 s. c om
 */
@Override
public String unsign(String message, File pemFile) {
    try {
        Security.addProvider(new BouncyCastleProvider());
        JCERSAPublicKey publicKey = readPublicKey(pemFile, "".toCharArray());

        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.DECRYPT_MODE, publicKey);

        // decryption:
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        baos.write(cipher.doFinal(org.bouncycastle.util.encoders.Base64.decode(message.getBytes("UTF-8"))));
        return baos.toString();
    } catch (IOException e) {
        throw new SdcRuntimeException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new SdcRuntimeException(e);
    } catch (InvalidKeyException e) {
        throw new SdcRuntimeException(e);
    } catch (NoSuchPaddingException e) {
        throw new SdcRuntimeException(e);
    } catch (IllegalBlockSizeException e) {
        throw new SdcRuntimeException(e);
    } catch (BadPaddingException e) {
        throw new SdcRuntimeException(e);
    }
}

From source file:com.thoughtworks.go.security.X509CertificateGenerator.java

License:Apache License

public X509CertificateGenerator() {
    Security.addProvider(new BouncyCastleProvider());
    this.keyStoreManager = new KeyStoreManager();
}

From source file:com.thoughtworks.go.server.util.HttpTestUtil.java

License:Apache License

public HttpTestUtil(final ContextCustomizer customizer) throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    serverKeyStore = createTempFile("server.jks");
    prepareCertStore(serverKeyStore);/*from ww w .  j  a v a  2 s.  co  m*/
    server = new Server();
    WebAppContext ctx = new WebAppContext();
    SessionHandler sh = new SessionHandler();
    ctx.setSessionHandler(sh);
    customizer.customize(ctx);
    ctx.setContextPath("/go");
    server.setHandler(ctx);
}

From source file:com.tremolosecurity.openunison.util.OpenUnisonUtils.java

License:Apache License

public static void main(String[] args) throws Exception {

    logger = org.apache.logging.log4j.LogManager.getLogger(OpenUnisonUtils.class.getName());

    Options options = new Options();
    options.addOption("unisonXMLFile", true, "The full path to the Unison xml file");
    options.addOption("keystorePath", true, "The full path to the Unison keystore");
    options.addOption("chainName", true, "The name of the authentication chain");
    options.addOption("mechanismName", true, "The name of the authentication mechanism for SAML2");
    options.addOption("idpName", true, "The name of the identity provider application");
    options.addOption("pathToMetaData", true, "The full path to the saml2 metadata file");
    options.addOption("createDefault", false, "If set, add default parameters");
    options.addOption("action", true,
            "export-sp-metadata, import-sp-metadata, export-secretkey, print-secretkey, import-idp-metadata, export-idp-metadata, clear-dlq, import-secretkey, create-secretkey");
    options.addOption("urlBase", true, "Base URL, no URI; https://host:port");
    options.addOption("alias", true, "Key alias");
    options.addOption("newKeystorePath", true, "Path to the new keystore");
    options.addOption("newKeystorePassword", true, "Password for the new keystore");
    options.addOption("help", false, "Prints this message");
    options.addOption("signMetadataWithKey", true, "Signs the metadata with the specified key");
    options.addOption("dlqName", true, "The name of the dead letter queue");
    options.addOption("upgradeFrom106", false, "Updates workflows from 1.0.6");
    options.addOption("secretkey", true, "base64 encoded secret key");
    options.addOption("envFile", true, "Environment variables for parmaterized configs");

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args, true);

    if (args.length == 0 || cmd.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("OpenUnisonUtils", options);
    }//from   w w  w . j  a v a 2 s.c  o m

    logger.info("Loading Unison Configuration");
    String unisonXMLFile = loadOption(cmd, "unisonXMLFile", options);
    TremoloType ttRead = loadTremoloType(unisonXMLFile, cmd, options);

    String action = loadOption(cmd, "action", options);
    TremoloType ttWrite = null;
    if (action.equalsIgnoreCase("import-sp-metadata") || action.equalsIgnoreCase("import-idp-metadata")) {
        ttWrite = loadTremoloType(unisonXMLFile);
    }

    logger.info("Configuration loaded");

    logger.info("Loading the keystore...");
    String ksPath = loadOption(cmd, "keystorePath", options);

    KeyStore ks = loadKeyStore(ksPath, ttRead);

    logger.info("...loaded");

    if (action.equalsIgnoreCase("import-sp-metadata")) {

        importMetaData(options, cmd, unisonXMLFile, ttRead, ttWrite, ksPath, ks);
    } else if (action.equalsIgnoreCase("export-sp-metadata")) {
        exportSPMetaData(options, cmd, ttRead, ks);

    } else if (action.equalsIgnoreCase("print-secretkey")) {
        printSecreyKey(options, cmd, ttRead, ks);
    } else if (action.equalsIgnoreCase("import-secretkey")) {
        importSecreyKey(options, cmd, ttRead, ks, ksPath);
    } else if (action.equalsIgnoreCase("create-secretkey")) {
        Security.addProvider(new BouncyCastleProvider());
        logger.info("Creating AES-256 secret key");
        String alias = loadOption(cmd, "alias", options);
        logger.info("Alias : '" + alias + "'");
        KeyGenerator kg = KeyGenerator.getInstance("AES", "BC");
        kg.init(256, new SecureRandom());
        SecretKey sk = kg.generateKey();
        ks.setKeyEntry(alias, sk, ttRead.getKeyStorePassword().toCharArray(), null);
        logger.info("Saving key");
        ks.store(new FileOutputStream(ksPath), ttRead.getKeyStorePassword().toCharArray());
        logger.info("Finished");
    } else if (action.equalsIgnoreCase("export-secretkey")) {
        logger.info("Export Secret Key");

        logger.info("Loading key");
        String alias = loadOption(cmd, "alias", options);
        SecretKey key = (SecretKey) ks.getKey(alias, ttRead.getKeyStorePassword().toCharArray());
        logger.info("Loading new keystore path");
        String pathToNewKeystore = loadOption(cmd, "newKeystorePath", options);
        logger.info("Loading new keystore password");
        String ksPassword = loadOption(cmd, "newKeystorePassword", options);

        KeyStore newKS = KeyStore.getInstance("PKCS12");
        newKS.load(null, ttRead.getKeyStorePassword().toCharArray());
        newKS.setKeyEntry(alias, key, ksPassword.toCharArray(), null);
        newKS.store(new FileOutputStream(pathToNewKeystore), ksPassword.toCharArray());
        logger.info("Exported");
    } else if (action.equalsIgnoreCase("import-idp-metadata")) {
        importIdpMetadata(options, cmd, unisonXMLFile, ttRead, ttWrite, ksPath, ks);

    } else if (action.equalsIgnoreCase("export-idp-metadata")) {
        exportIdPMetadata(options, cmd, ttRead, ks);
    } else if (action.equalsIgnoreCase("clear-dlq")) {
        logger.info("Getting the DLQ Name...");
        String dlqName = loadOption(cmd, "dlqName", options);
        QueUtils.emptyDLQ(ttRead, dlqName);
    } else if (action.equalsIgnoreCase("upgradeFrom106")) {
        logger.info("Upgrading OpenUnison's configuration from 1.0.6");

        String backupFileName = unisonXMLFile + ".bak";

        logger.info("Backing up to '" + backupFileName + "'");

        BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(unisonXMLFile)));
        PrintWriter out = new PrintWriter(new FileOutputStream(backupFileName));
        String line = null;
        while ((line = in.readLine()) != null) {
            out.println(line);
        }
        out.flush();
        out.close();
        in.close();

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        AddChoiceToTasks.convert(new FileInputStream(unisonXMLFile), bout);
        FileOutputStream fsout = new FileOutputStream(unisonXMLFile);
        fsout.write(bout.toByteArray());
        fsout.flush();
        fsout.close();

    }

}

From source file:com.trsst.Command.java

License:Apache License

public static void main(String[] argv) {

    // during alpha period: expire after one week
    Date builtOn = Common.getBuildDate();
    if (builtOn != null) {
        long weekMillis = 1000 * 60 * 60 * 24 * 7;
        Date expiry = new Date(builtOn.getTime() + weekMillis);
        if (new Date().after(expiry)) {
            System.err.println("Build expired on: " + expiry);
            System.err.println("Please obtain a more recent build for testing.");
            System.exit(1);/*from  w  w w .  jav a  2  s  .c o m*/
        } else {
            System.err.println("Build will expire on: " + expiry);
        }
    }

    // experimental tor support
    boolean wantsTor = false;
    for (String s : argv) {
        if ("--tor".equals(s)) {
            wantsTor = true;
            break;
        }
    }
    if (wantsTor && !HAS_TOR) {
        try {
            log.info("Attempting to connect to tor network...");
            Security.addProvider(new BouncyCastleProvider());
            JvmGlobalUtil.init();
            NetLayer netLayer = NetFactory.getInstance().getNetLayerById(NetLayerIDs.TOR);
            JvmGlobalUtil.setNetLayerAndNetAddressNameService(netLayer, true);
            log.info("Connected to tor network");
            HAS_TOR = true;
        } catch (Throwable t) {
            log.error("Could not connect to tor: exiting", t);
            System.exit(1);
        }
    }

    // if unspecified, default relay to home.trsst.com
    if (System.getProperty("com.trsst.server.relays") == null) {
        System.setProperty("com.trsst.server.relays", "https://home.trsst.com/feed");
    }

    // default to user-friendlier file names
    String home = System.getProperty("user.home", ".");
    if (System.getProperty("com.trsst.client.storage") == null) {
        File client = new File(home, "Trsst Accounts");
        System.setProperty("com.trsst.client.storage", client.getAbsolutePath());
    }
    if (System.getProperty("com.trsst.server.storage") == null) {
        File server = new File(home, "Trsst System Cache");
        System.setProperty("com.trsst.server.storage", server.getAbsolutePath());
    }
    // TODO: try to detect if launching from external volume like a flash
    // drive and store on the local flash drive instead

    Console console = System.console();
    int result;
    try {
        if (console == null && argv.length == 0) {
            argv = new String[] { "serve", "--gui" };
        }
        result = new Command().doBegin(argv, System.out, System.in);

        // task queue prevents exit unless stopped
        if (TrsstAdapter.TASK_QUEUE != null) {
            TrsstAdapter.TASK_QUEUE.cancel();
        }
    } catch (Throwable t) {
        result = 1; // "general catchall error code"
        log.error("Unexpected error, exiting.", t);
    }

    // if error
    if (result != 0) {
        // force exit
        System.exit(result);
    }
}

From source file:com.trustly.api.security.KeyChain.java

License:Open Source License

/**
 * Loads the Trustly public key.//from   w w w. j  a  v a2  s. c  o m
 * @param testEnvironment whether to load the key for test environment or not.
 */
private void loadTrustlyPublicKey(final boolean testEnvironment) {
    try {
        final File file = testEnvironment ? new File(TEST_TRUSTLY_PUBLIC_KEY_PATH)
                : new File(LIVE_TRUSTLY_PUBLIC_KEY_PATH);

        final PEMParser pemParser = new PEMParser(new FileReader(file));
        final PemObject object = pemParser.readPemObject();

        final JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider(new BouncyCastleProvider());

        final byte[] encoded = object.getContent();
        final SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo(
                ASN1Sequence.getInstance(encoded));

        trustlyPublicKey = converter.getPublicKey(subjectPublicKeyInfo);
    } catch (final IOException e) {
        throw new TrustlyAPIException("Failed to load Trustly public key", e);
    }
}

From source file:com.Utilities.PinBlock.java

public String pinProcess(String PIN, String PAN, String key) {

    try {//from ww  w. ja  v  a  2  s. com
        Security.addProvider(new BouncyCastleProvider());

        //         String PIN = "1007";
        //        String PAN = "6396730416041961";
        //        String key = "26EA89DCA810CB8CBC19BA4C26C7943426EA89DCA810CB8C";
        //
        PinBlock p = new PinBlock();

        byte[] plain = p.processPinPan(PIN, PAN);

        byte[] keyBytes = HexString2Bytes(key);

        SecretKey keySpec = new SecretKeySpec(keyBytes, "DESede");

        IvParameterSpec iv = new IvParameterSpec(new byte[8]);

        Cipher e_cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding", "BC");

        e_cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);

        byte[] cipherText = e_cipher.doFinal(plain);
        //  System.out.println("Ciphertext: " + Bytes2HexString(cipherText).substring(0, 16));
        return Bytes2HexString(cipherText).substring(0, 16);
    } // end main
    catch (InvalidKeyException ex) {
        Logger.getLogger(PinBlock.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidAlgorithmParameterException ex) {
        Logger.getLogger(PinBlock.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalBlockSizeException ex) {
        Logger.getLogger(PinBlock.class.getName()).log(Level.SEVERE, null, ex);
    } catch (BadPaddingException ex) {
        Logger.getLogger(PinBlock.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(PinBlock.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchProviderException ex) {
        Logger.getLogger(PinBlock.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchPaddingException ex) {
        Logger.getLogger(PinBlock.class.getName()).log(Level.SEVERE, null, ex);
    }

    return "";
}