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.bitsofproof.supernode.test.APITest.java

License:Apache License

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

From source file:com.brienwheeler.apps.tomcat.TomcatBean.java

License:Open Source License

private RSAPrivateKey readKeyFile() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    String parse[] = readPEMFile(sslKeyFile, KEY_PATTERN, 2);
    if (parse == null)
        throw new IllegalArgumentException("invalid key file contents");

    if (parse[0].length() == 0) { // BEGIN PRIVATE KEY
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return (RSAPrivateKey) keyFactory.generatePrivate(new PKCS8EncodedKeySpec(Base64.decode(parse[1])));
    }/*from   www .  j av  a  2  s . c o m*/

    if (parse[0].contains("RSA")) { // BEGIN RSA PRIVATE KEY
        Security.addProvider(new BouncyCastleProvider());

        PEMParser pemParser = new PEMParser(new FileReader(sslKeyFile));
        Object parsedObject = pemParser.readObject();
        if (!(parsedObject instanceof PEMKeyPair))
            throw new IllegalArgumentException("invalid key file contents");

        PEMKeyPair keyPair = (PEMKeyPair) parsedObject;
        RSAPrivateKey privateKey = (RSAPrivateKey) BouncyCastleProvider
                .getPrivateKey(keyPair.getPrivateKeyInfo());
        if (privateKey == null)
            throw new IllegalArgumentException("invalid key file contents");
        return privateKey;
    }

    throw new IllegalArgumentException("invalid key file contents");
}

From source file:com.btmatthews.maven.plugins.crx.CRXArchiverImpl.java

License:Apache License

/**
 * Generate an in-memory ZIP file containing the resources for the Google Chrome Extension, then sign the ZIP
 * and write out a CRX file containing the header, signature, public key and ZIP data.
 *///from w w  w  . j ava 2  s . c  o  m
@Override
protected void execute() {

    try {
        Security.addProvider(new BouncyCastleProvider());

        // ZIP the CRX source directory tree

        final byte[] zipData = createZipFile();

        // Get the public/private key and sign the ZIP

        final KeyPair keyPair = getKeyPair();
        byte[] publicKey = keyPair.getPublic().getEncoded();
        byte[] signature = signatureHelper.sign(zipData, keyPair.getPrivate());

        // Write the CRX file

        final CRXArchive archive = new CRXArchive(publicKey, signature, zipData);
        archiveHelper.writeArchive(getDestFile(), archive);
    } catch (final GeneralSecurityException e) {
        throw new ArchiverException("Could not generate the signature for the CRX file", e);
    } catch (final IOException e) {
        throw new ArchiverException("Could not read resources or output the CRX file", e);
    }
}

From source file:com.btmatthews.maven.plugins.crx.TestSignatureHelper.java

License:Apache License

/**
 * Prepare for the unit tests.//  www  . jav a 2  s. c o  m
 *
 * @throws Exception If there was a problem preparing for the unit tests.
 */
@Before
public void setUp() throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    signatureHelper = new CRXSignatureHelper();
    keyFactory = KeyFactory.getInstance("RSA", "BC");
}

From source file:com.chiorichan.net.NetworkManager.java

License:Mozilla Public License

public static void startHttpsServer() throws StartupException {
    if (httpsChannel != null && httpsChannel.isOpen())
        throw new StartupException("The HTTPS Server is already running");

    try {/*  w ww .j ava  2  s . c  o m*/
        InetSocketAddress socket;
        String httpIp = AppConfig.get().getString("server.httpHost", "");
        int httpsPort = AppConfig.get().getInt("server.httpsPort", 8443);

        Security.addProvider(new BouncyCastleProvider());

        if (httpsPort >= 1) {
            if (Application.isPrivilegedPort(httpsPort)) {
                getLogger().warning(
                        "It would seem that you are trying to start ChioriWebServer's Web Server (SSL) on a privileged port without root access.");
                getLogger().warning(
                        "Most likely you will see an exception thrown below this. http://www.w3.org/Daemon/User/Installation/PrivilegedPorts.html");
                getLogger().warning(
                        "It's recommended that you either run CWS (SSL) on a port like 4443 then use the firewall to redirect from 443 or run as root if you must use port: "
                                + httpsPort);
            }

            if (httpIp.isEmpty())
                socket = new InetSocketAddress(httpsPort);
            else
                socket = new InetSocketAddress(httpIp, httpsPort);

            AppManager.manager(SslManager.class).init();

            getLogger().info(
                    "Starting Secure Web Server on " + (httpIp.isEmpty() ? "*" : httpIp) + ":" + httpsPort);

            try {
                ServerBootstrap b = new ServerBootstrap();
                b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                        .childHandler(new SslInitializer());

                httpsChannel = b.bind(socket).sync().channel();

                // HTTPS Server Thread
                AppController.registerRunnable(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            httpsChannel.closeFuture().sync();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        getLogger().info("The HTTPS Server has been shutdown!");
                    }
                });
            } catch (NullPointerException e) {
                throw new StartupException(
                        "There was a problem starting the Web Server. Check logs and try again.", e);
            } catch (Throwable e) {
                getLogger().warning("**** FAILED TO BIND HTTPS SERVER TO PORT!");
                getLogger().warning("Perhaps a server is already running on that port?");

                throw new StartupException(e);
            }
        } else
            getLogger().warning("The HTTPS server is disabled per configs.");
    } catch (Throwable e) {
        throw new StartupException(e);
    }
}

From source file:com.clienteweb.CifrarRSAFicheros.java

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

    String nombre = "server1024";
    try {/*w  w w.j a  v a  2 s  .co m*/
        // Anadir provider JCE (provider por defecto no soporta RSA)
        Security.addProvider(new BouncyCastleProvider()); // Cargar el provider BC
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        Cipher cifrador = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
        // PASO 2: Crear cifrador RSA
        //  Cipher cifrador =Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC"); // Hace uso del provider BC
        /************************************************************************
         * IMPORTANTE: En BouncyCastle el algoritmo RSA no funciona realmente en modo ECB
         *        * No divide el mensaje de entrada en bloques
         *                  * Solo cifra los primeros 512 bits (tam. clave)
         *        * Para cifrar mensajes mayores, habra que hacer la
         *                    divisin en bloques "a mano"
         ************************************************************************/

        /*** Crear KeyFactory (depende del provider) usado para las transformaciones de claves*/
        KeyFactory keyFactoryRSA = KeyFactory.getInstance("RSA", "BC"); // Hace uso del provider BC
        /*** 4 Recuperar clave PUBLICA del fichero */
        // 4.1 Leer datos binarios x809
        byte[] bufferPub = new byte[162];
        FileInputStream in = new FileInputStream(nombre + ".publica");
        DataInputStream d = new DataInputStream(in);
        d.readFully(bufferPub, 0, 162);
        //in.read(bufferPub, 0, 5000);
        in.close();

        // 4.2 Recuperar clave publica desde datos codificados en formato X509
        X509EncodedKeySpec clavePublicaSpec = new X509EncodedKeySpec(bufferPub);
        PublicKey clavePublica2 = keyFactoryRSA.generatePublic(clavePublicaSpec);

        // PASO 3a: Poner cifrador en modo CIFRADO
        cifrador.init(Cipher.ENCRYPT_MODE, clavePublica2); // Cifra con la clave publica

        System.out.println("3a. Cifrar con clave publica");

        String sinCifrar = "12345678901234567890123456789012345678901234567890123456789esto no puede ser";
        sinCifrar += "kokokokok";//sinCifrar = "12asdad  ";
        System.out.println(sinCifrar.getBytes("UTF-8").length);
        byte[] partes = new byte[100];

        byte[] bufferCifrado = new byte[5000];
        byte[] buffer = sinCifrar.getBytes("UTF-8");

        cifrador.doFinal(buffer);

        System.out.println("TEXTO CIFRADO" + bufferCifrado.length);
        mostrarBytes(bufferCifrado);
        bufferCifrado = Base64.encodeBase64(bufferCifrado);
        System.out.println("\n-------------------------------");

        // PASO 3b: Poner cifrador en modo DESCIFRADO

        /*** 2 Recuperar clave Privada del fichero */
        // 2.1 Leer datos binarios PKCS8
        byte[] bufferPriv = new byte[5000];
        in = new FileInputStream(nombre + ".privada");
        int chars = in.read(bufferPriv, 0, 5000);
        in.close();

        byte[] bufferPriv2 = new byte[chars];
        System.arraycopy(bufferPriv, 0, bufferPriv2, 0, chars);

        // 2.2 Recuperar clave privada desde datos codificados en formato PKCS8
        PKCS8EncodedKeySpec clavePrivadaSpec = new PKCS8EncodedKeySpec(bufferPriv2);

        PrivateKey clavePrivada2 = keyFactoryRSA.generatePrivate(clavePrivadaSpec);

        cifrador.init(Cipher.DECRYPT_MODE, clavePrivada2); // Descrifra con la clave privada

        System.out.println("3b. Descifrar con clave privada");
        byte[] bufferPlano2 = cifrador.doFinal(bufferCifrado);

        System.out.println("TEXTO DESCIFRADO");
        mostrarBytes(bufferPlano2);
        mostrarBytes(cifrador.doFinal(Base64.decodeBase64(bufferCifrado)));

        System.out.println("\n-------------------------------");
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(CifrarRSAFicheros.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchPaddingException ex) {
        Logger.getLogger(CifrarRSAFicheros.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(CifrarRSAFicheros.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeyException ex) {
        Logger.getLogger(CifrarRSAFicheros.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeySpecException ex) {
        Logger.getLogger(CifrarRSAFicheros.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalBlockSizeException ex) {
        Logger.getLogger(CifrarRSAFicheros.class.getName()).log(Level.SEVERE, null, ex);
    } catch (BadPaddingException ex) {
        Logger.getLogger(CifrarRSAFicheros.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchProviderException ex) {
        Logger.getLogger(CifrarRSAFicheros.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.clienteweb.ClienteWebCifrado.java

public static void main(String[] args) {

    final String url = "http://quevedo2dam.azurewebsites.net";
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {//  ww w  .j  av a 2  s . c  o  m
        HttpGet httpGet = new HttpGet(url + "/login");
        HttpClientContext context = HttpClientContext.create();

        CloseableHttpResponse response1 = httpclient.execute(httpGet, context);
        // The underlying HTTP connection is still held by the response object
        // to allow the response content to be streamed directly from the network socket.
        // In order to ensure correct deallocation of system resources
        // the user MUST call CloseableHttpResponse#close() from a finally clause.
        // Please note that if response content is not fully consumed the underlying
        // connection cannot be safely re-used and will be shut down and discarded
        // by the connection manager.

        System.out.println(response1.getStatusLine());
        HttpEntity entity1 = response1.getEntity();
        // do something useful with the response body
        // and ensure it is fully consumed
        String content = EntityUtils.toString(entity1);
        System.out.println(content);
        //descodifico
        byte[] clave = Base64.decodeBase64(content);
        //descifro
        byte[] bufferPub = new byte[5000];
        FileInputStream in = new FileInputStream(new File("server1024.publica"));
        int chars = in.read(bufferPub, 0, 5000);
        in.close();

        byte[] bufferPub2 = new byte[chars];
        System.arraycopy(bufferPub, 0, bufferPub2, 0, chars);

        Security.addProvider(new BouncyCastleProvider()); // Cargar el provider BC
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        Cipher cifrador = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");

        KeyFactory keyFactoryRSA = KeyFactory.getInstance("RSA", "BC"); // Hace uso del provider BC
        // 4.2 Recuperar clave publica desde datos codificados en formato X509
        X509EncodedKeySpec clavePublicaSpec = new X509EncodedKeySpec(bufferPub2);
        PublicKey clavePublica2 = keyFactoryRSA.generatePublic(clavePublicaSpec);

        cifrador.init(Cipher.DECRYPT_MODE, clavePublica2); // Descrifra con la clave privada

        byte[] claveAES = cifrador.doFinal(clave);

        SecretKey originalKey = new SecretKeySpec(claveAES, 0, claveAES.length, "AES");

        //descodifico la key del AES
        // la convierto a key

        System.out.println("----Segunda llamada");
        httpGet = new HttpGet(url + "/juegos?command=get");

        response1 = httpclient.execute(httpGet, context);

        entity1 = response1.getEntity();
        // do something useful with the response body
        // and ensure it is fully consumed
        content = EntityUtils.toString(entity1);

        System.out.println(content);
        ObjectMapper mapper = new ObjectMapper();

        System.out.println(descifra(Base64.decodeBase64(content), originalKey));

        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        ArrayList<Juego> j = mapper.readValue(descifra(Base64.decodeBase64(content), originalKey),
                new TypeReference<ArrayList<Juego>>() {
                });
        System.out.println(j.get(0).getNombre());
        response1.close();

    } catch (IOException ex) {
        Logger.getLogger(ClienteWebCifrado.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(ClienteWebCifrado.class.getName()).log(Level.SEVERE, null, ex);
    } finally {

    }
}

From source file:com.cloud.api.ApiServer.java

License:Apache License

@Override
public boolean start() {
    Security.addProvider(new BouncyCastleProvider());
    Integer apiPort = null; // api port, null by default
    final SearchCriteria<ConfigurationVO> sc = configDao.createSearchCriteria();
    sc.addAnd("name", SearchCriteria.Op.EQ, Config.IntegrationAPIPort.key());
    final List<ConfigurationVO> values = configDao.search(sc, null);
    if ((values != null) && (values.size() > 0)) {
        final ConfigurationVO apiPortConfig = values.get(0);
        if (apiPortConfig.getValue() != null) {
            apiPort = Integer.parseInt(apiPortConfig.getValue());
        }// w w  w. j av  a  2  s .  c o  m
    }

    final Map<String, String> configs = configDao.getConfiguration();
    final String strSnapshotLimit = configs.get(Config.ConcurrentSnapshotsThresholdPerHost.key());
    if (strSnapshotLimit != null) {
        final Long snapshotLimit = NumbersUtil.parseLong(strSnapshotLimit, 1L);
        if (snapshotLimit.longValue() <= 0) {
            s_logger.debug("Global config parameter " + Config.ConcurrentSnapshotsThresholdPerHost.toString()
                    + " is less or equal 0; defaulting to unlimited");
        } else {
            dispatcher.setCreateSnapshotQueueSizeLimit(snapshotLimit);
        }
    }

    final Set<Class<?>> cmdClasses = new HashSet<Class<?>>();
    for (final PluggableService pluggableService : pluggableServices) {
        cmdClasses.addAll(pluggableService.getCommands());
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Discovered plugin " + pluggableService.getClass().getSimpleName());
        }
    }

    for (final Class<?> cmdClass : cmdClasses) {
        final APICommand at = cmdClass.getAnnotation(APICommand.class);
        if (at == null) {
            throw new CloudRuntimeException(
                    String.format("%s is claimed as a API command, but it doesn't have @APICommand annotation",
                            cmdClass.getName()));
        }

        String apiName = at.name();
        List<Class<?>> apiCmdList = s_apiNameCmdClassMap.get(apiName);
        if (apiCmdList == null) {
            apiCmdList = new ArrayList<Class<?>>();
            s_apiNameCmdClassMap.put(apiName, apiCmdList);
        }
        apiCmdList.add(cmdClass);

    }

    setEncodeApiResponse(Boolean.valueOf(configDao.getValue(Config.EncodeApiResponse.key())));

    if (apiPort != null) {
        final ListenerThread listenerThread = new ListenerThread(this, apiPort);
        listenerThread.start();
    }

    return true;
}

From source file:com.coinessa.btc.key.helper.BIP39.java

License:Apache License

public BIP39() {
    Security.addProvider(new BouncyCastleProvider());
    worldList = ResourcesUtil.readString(getClass(), worldListResource).split(" ");
}

From source file:com.computersecurity.hybridcryptography.model.moduleDES.DESBaseCBC.java

public DESBaseCBC() {
    try {//from   w  w  w .j a v a  2s  .  c  o  m
        Security.addProvider(new BouncyCastleProvider());
        rounds = 0;
        cipher = Cipher.getInstance(ALGORITHM, PROVIDER);
        secureRand = SecureRandom.getInstance("SHA1PRNG");
        secureRand.nextBytes(new byte[cipher.getBlockSize()]);
        ivParamSpec = new IvParameterSpec(new byte[cipher.getBlockSize()]);

    } catch (NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException ex) {

        System.out.println(ex);

    }

}