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

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

Introduction

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

Prototype

String PROVIDER_NAME

To view the source code for org.bouncycastle.jce.provider BouncyCastleProvider PROVIDER_NAME.

Click Source Link

Usage

From source file:eu.stratuslab.ssl.GridSslContextFactory.java

License:Apache License

private void registerCryptoServiceProvider() {

    if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
        LOGGER.info("registering {} provider", BouncyCastleProvider.PROVIDER_NAME);
        Security.addProvider(new BouncyCastleProvider());
    }// w w w . j  av a2 s .c  om

}

From source file:ezbake.crypto.RSAKeyCrypto.java

License:Apache License

public RSAKeyCrypto(byte[] key, boolean isPrivate) throws NoSuchAlgorithmException, InvalidKeySpecException {
    KeySpec keySpec;//from  w ww. j a  v  a2s  .  c  o m

    KeyFactory keyFactory;
    try {
        keyFactory = KeyFactory.getInstance(keyAlgorithm, BouncyCastleProvider.PROVIDER_NAME);
    } catch (NoSuchProviderException e) {
        log.info("Unable to use the bouncycastle provider for RSA key factory. using default");
        keyFactory = KeyFactory.getInstance(keyAlgorithm);
    }

    if (isPrivate) {
        keySpec = new PKCS8EncodedKeySpec(key);
        this.privateKey = keyFactory.generatePrivate(keySpec);

        RSAPrivateCrtKey rpk = (RSAPrivateCrtKey) privateKey;
        RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(rpk.getModulus(), rpk.getPublicExponent());

        try {
            this.publicKey = keyFactory.generatePublic(publicKeySpec);
        } catch (Exception e) {
            log.error("ERROR: {}", e);
        }
    } else {
        try {
            keySpec = new X509EncodedKeySpec(key);
            this.publicKey = keyFactory.generatePublic(keySpec);
        } catch (InvalidKeySpecException e) {
            this.publicKey = fixPubKey(key);
        }
    }
}

From source file:ezbake.crypto.RSAKeyCrypto.java

License:Apache License

public RSAKeyCrypto(byte[] privateKey, byte[] publicKey)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    KeyFactory keyFactory;//from   ww  w .ja v a  2  s  . c o  m
    try {
        keyFactory = KeyFactory.getInstance(keyAlgorithm, BouncyCastleProvider.PROVIDER_NAME);
    } catch (NoSuchProviderException e) {
        log.info("Unable to use the bouncycastle provider for RSA key factory. using default");
        keyFactory = KeyFactory.getInstance(keyAlgorithm);
    }

    KeySpec keySpec = new PKCS8EncodedKeySpec(privateKey);
    this.privateKey = keyFactory.generatePrivate(keySpec);

    if (publicKey != null) {
        try {
            keySpec = new X509EncodedKeySpec(publicKey);
            this.publicKey = keyFactory.generatePublic(keySpec);
        } catch (InvalidKeySpecException e) {
            this.publicKey = fixPubKey(publicKey);
        } catch (IllegalArgumentException e) {
            this.publicKey = fixPubKey(publicKey);
        }
    }
}

From source file:fabric.common.Crypto.java

License:Open Source License

/**
 * Validates the given certificate chain against the given trust store.
 *///from w  ww .j a va  2s.  c o  m
public static void validateCertificateChain(Certificate[] certificateChain, Set<TrustAnchor> trustStore)
        throws GeneralSecurityException {
    PKIXParameters params = new PKIXParameters(trustStore);
    params.setSigProvider(BouncyCastleProvider.PROVIDER_NAME);
    params.setRevocationEnabled(false);
    CertificateFactory certFactory = CertificateFactory.getInstance("X509");
    CertPath certPath = certFactory.generateCertPath(Arrays.asList(certificateChain));
    CertPathValidator pathValidator = CertPathValidator.getInstance("PKIX");
    pathValidator.validate(certPath, params);
}

From source file:gobblin.crypto.GPGFileDecryptor.java

License:Apache License

public static InputStream decryptFile(InputStream inputStream, String passPhrase) throws IOException {

    if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
        Security.addProvider(new BouncyCastleProvider());
    }/*ww  w.ja v  a 2  s . c om*/
    inputStream = PGPUtil.getDecoderStream(inputStream);

    JcaPGPObjectFactory pgpF = new JcaPGPObjectFactory(inputStream);
    PGPEncryptedDataList enc;
    Object pgpfObject = pgpF.nextObject();

    if (pgpfObject instanceof PGPEncryptedDataList) {
        enc = (PGPEncryptedDataList) pgpfObject;
    } else {
        enc = (PGPEncryptedDataList) pgpF.nextObject();
    }

    PGPPBEEncryptedData pbe = (PGPPBEEncryptedData) enc.get(0);

    InputStream clear;
    try {
        clear = pbe
                .getDataStream(new JcePBEDataDecryptorFactoryBuilder(new JcaPGPDigestCalculatorProviderBuilder()
                        .setProvider(BouncyCastleProvider.PROVIDER_NAME).build())
                                .setProvider(BouncyCastleProvider.PROVIDER_NAME)
                                .build(passPhrase.toCharArray()));

        JcaPGPObjectFactory pgpFact = new JcaPGPObjectFactory(clear);
        pgpfObject = pgpFact.nextObject();
        if (pgpfObject instanceof PGPCompressedData) {
            PGPCompressedData cData = (PGPCompressedData) pgpfObject;
            pgpFact = new JcaPGPObjectFactory(cData.getDataStream());
            pgpfObject = pgpFact.nextObject();
        }

        PGPLiteralData ld = (PGPLiteralData) pgpfObject;
        return ld.getInputStream();
    } catch (PGPException e) {
        throw new IOException(e);
    }
}

From source file:gobblin.util.GPGFileDecrypter.java

License:Open Source License

public static FSDataInputStream decryptFile(InputStream inputStream, String passPhrase) throws IOException {

    if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
        Security.addProvider(new BouncyCastleProvider());
    }/*from   w w  w . j  av  a  2  s  .c  o  m*/
    inputStream = PGPUtil.getDecoderStream(inputStream);

    JcaPGPObjectFactory pgpF = new JcaPGPObjectFactory(inputStream);
    PGPEncryptedDataList enc;
    Object pgpfObject = pgpF.nextObject();

    if (pgpfObject instanceof PGPEncryptedDataList) {
        enc = (PGPEncryptedDataList) pgpfObject;
    } else {
        enc = (PGPEncryptedDataList) pgpF.nextObject();
    }

    PGPPBEEncryptedData pbe = (PGPPBEEncryptedData) enc.get(0);

    InputStream clear;
    try {
        clear = pbe
                .getDataStream(new JcePBEDataDecryptorFactoryBuilder(new JcaPGPDigestCalculatorProviderBuilder()
                        .setProvider(BouncyCastleProvider.PROVIDER_NAME).build())
                                .setProvider(BouncyCastleProvider.PROVIDER_NAME)
                                .build(passPhrase.toCharArray()));

        JcaPGPObjectFactory pgpFact = new JcaPGPObjectFactory(clear);
        pgpfObject = pgpFact.nextObject();
        if (pgpfObject instanceof PGPCompressedData) {
            PGPCompressedData cData = (PGPCompressedData) pgpfObject;
            pgpFact = new JcaPGPObjectFactory(cData.getDataStream());
            pgpfObject = pgpFact.nextObject();
        }

        PGPLiteralData ld = (PGPLiteralData) pgpfObject;
        return StreamUtils.convertStream(ld.getInputStream());
    } catch (PGPException e) {
        throw new IOException(e);
    }
}

From source file:google.registry.testing.BouncyCastleProviderRule.java

License:Open Source License

@Override
protected void after() {
    Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
}

From source file:io.spikex.core.Main.java

License:Apache License

private void createKeyStore(final YamlDocument conf) {

    YamlDocument confKeyStore = conf.getDocument(CONF_KEY_KEYSTORE);
    boolean generate = confKeyStore.getValue(CONF_KEY_GENERATE, DEF_GENERATE_KEYSTORE);

    if (generate) {

        Path keyStorePath = Paths
                .get(confKeyStore.getValue(CONF_KEY_PATH, m_confPath.resolve(DEF_KEYSTORE_PATH).toString()))
                .toAbsolutePath().normalize();

        if (!Files.exists(keyStorePath)) {

            Provider bcProvider = Security.getProvider(BouncyCastleProvider.PROVIDER_NAME);
            if (bcProvider == null) {
                Security.addProvider(new BouncyCastleProvider());
            }/*from  w w w  . j  a  va  2 s.  c om*/

            String password = confKeyStore.getValue(CONF_KEY_PASSWORD, DEF_KEYSTORE_PASSWORD);
            String hostFqdn = confKeyStore.getValue(CONF_KEY_HOST_FQDN, HostOs.hostName());
            List<String> subjAltNames = confKeyStore.getValue(CONF_KEY_SUBJECT_ALT_NAME, new ArrayList());

            try (FileOutputStream out = new FileOutputStream(keyStorePath.toFile())) {

                m_logger.info("Generating keystore: {}", keyStorePath);

                KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA",
                        BouncyCastleProvider.PROVIDER_NAME);

                SecureRandom rnd = new SecureRandom();
                generator.initialize(2048, rnd);
                KeyPair pair = generator.generateKeyPair();

                // DN
                X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
                nameBuilder.addRDN(BCStyle.C, System.getProperty("user.country.format", "NU"));
                nameBuilder.addRDN(BCStyle.OU, "Self-signed test certificate");
                nameBuilder.addRDN(BCStyle.OU, "For testing purposes only");
                nameBuilder.addRDN(BCStyle.O, "Spike.x");
                nameBuilder.addRDN(BCStyle.CN, hostFqdn);

                long oneDay = 24 * 60 * 60 * 1000;
                Date notBefore = new Date(System.currentTimeMillis() - oneDay); // Yesterday
                Date notAfter = new Date(System.currentTimeMillis() + (oneDay * 3 * 365)); // 3 years

                BigInteger serialNum = BigInteger.valueOf(rnd.nextLong());
                X509v3CertificateBuilder x509v3Builder = new JcaX509v3CertificateBuilder(nameBuilder.build(),
                        serialNum, notBefore, notAfter, nameBuilder.build(), pair.getPublic());

                //
                // Extensions
                //
                x509v3Builder.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
                x509v3Builder.addExtension(X509Extensions.KeyUsage, true,
                        new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
                x509v3Builder.addExtension(X509Extensions.ExtendedKeyUsage, true,
                        new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));

                GeneralName[] dnsNames = new GeneralName[subjAltNames.size()];
                for (int i = 0; i < subjAltNames.size(); i++) {
                    String name = subjAltNames.get(i);
                    m_logger.info("Adding subject alt name: {}", name);
                    dnsNames[i] = new GeneralName(GeneralName.dNSName, name);
                }
                x509v3Builder.addExtension(X509Extensions.SubjectAlternativeName, false,
                        new GeneralNames(dnsNames));

                ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption")
                        .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(pair.getPrivate());

                X509Certificate cert = new JcaX509CertificateConverter()
                        .setProvider(BouncyCastleProvider.PROVIDER_NAME)
                        .getCertificate(x509v3Builder.build(signer));

                // Validate
                cert.checkValidity(new Date());
                cert.verify(cert.getPublicKey());

                // Save in keystore
                KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
                ks.load(null);
                ks.setKeyEntry(hostFqdn, pair.getPrivate(), password.toCharArray(), new Certificate[] { cert });

                m_logger.info("Created self-signed certificate: {}", hostFqdn);
                ks.store(out, password.toCharArray());

            } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException
                    | NoSuchProviderException | OperatorCreationException | InvalidKeyException
                    | SignatureException e) {
                throw new RuntimeException("Failed to create keystore: " + keyStorePath, e);
            }
        }
    }
}

From source file:io.spikex.core.Main.java

License:Apache License

private void createTrustStore(final YamlDocument conf) {

    YamlDocument confTrustStore = conf.getDocument(CONF_KEY_TRUSTSTORE);
    boolean generate = confTrustStore.getValue(CONF_KEY_GENERATE, DEF_GENERATE_TRUSSTORE);

    if (generate) {

        Path trustStorePath = Paths
                .get(confTrustStore.getValue(CONF_KEY_PATH, m_confPath.resolve(DEF_TRUSTSTORE_PATH)).toString())
                .toAbsolutePath().normalize();

        Path certsPath = m_confPath.resolve(DEF_TRUSTSTORE_CERTS_DIR).toAbsolutePath().normalize();

        if (!Files.exists(trustStorePath) && Files.exists(certsPath)) {

            Provider bcProvider = Security.getProvider(BouncyCastleProvider.PROVIDER_NAME);
            if (bcProvider == null) {
                Security.addProvider(new BouncyCastleProvider());
            }//ww  w  .  j  av  a2  s .  c om
            try {
                // Create keystore
                m_logger.info("Generating truststore: {}", trustStorePath);
                KeyStore ts = KeyStore.getInstance(KeyStore.getDefaultType());
                ts.load(null);

                //
                // Import PEM certificates
                // https://gist.github.com/akorobov/6910564
                //
                try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(certsPath)) {

                    JcaX509CertificateConverter converter = new JcaX509CertificateConverter()
                            .setProvider(BouncyCastleProvider.PROVIDER_NAME);

                    for (Path path : dirStream) {
                        PEMParser parser = new PEMParser(new FileReader(path.toFile()));

                        while (true) {
                            int index = 1;
                            Object object = parser.readObject();

                            if (object != null) {
                                if (object instanceof X509CertificateHolder) {
                                    X509Certificate cert = converter
                                            .getCertificate((X509CertificateHolder) object);

                                    m_logger.debug(
                                            "Certificate issuer: {} subject: {} serial: {} validity: {}-{}",
                                            cert.getIssuerX500Principal().getName(),
                                            cert.getSubjectX500Principal().getName(), cert.getSerialNumber(),
                                            cert.getNotBefore(), cert.getNotAfter());

                                    // Validate
                                    cert.checkValidity(new Date());

                                    // Alias
                                    String alias = cert.getSubjectX500Principal().getName();
                                    if (Strings.isNullOrEmpty(alias)) {
                                        alias = "cert-" + index++;
                                    }

                                    // Save in trusstore
                                    ts.setCertificateEntry(alias, cert);
                                    m_logger.info("Imported trusted certificate: {}", alias);
                                }
                            } else {
                                break;
                            }
                        }
                    }
                } catch (CertificateException e) {
                    m_logger.error("Failed to import trusted certificate", e);
                }

                // Save truststore
                String password = confTrustStore.getValue(CONF_KEY_PASSWORD, DEF_TRUSTSTORE_PASSWORD);
                ts.store(new FileOutputStream(trustStorePath.toFile()), password.toCharArray());

            } catch (IOException | NoSuchAlgorithmException | KeyStoreException | CertificateException e) {
                throw new RuntimeException("Failed to create truststore: " + trustStorePath, e);
            }
        }
    }
}

From source file:io.spikex.filter.output.Nsq.java

License:Apache License

@Override
protected void startFilter() {

    ///*from w w w  .  java 2s .c o m*/
    // Use Bouncy Castle as our security provider
    // Needed for PKCS#8 parsing
    //
    Provider bcProvider = Security.getProvider(BouncyCastleProvider.PROVIDER_NAME);
    if (bcProvider == null) {
        Security.addProvider(new BouncyCastleProvider());
    }

    NsqClientConfig config = NsqClientConfig.builder(config()).build();
    List<String> nodes = config.getNodes();

    // Sanity checks
    Preconditions.checkArgument(nodes.size() > 0, "No nodes defined");

    //
    // Topics
    //
    m_topics = new ArrayList();
    JsonArray topics = config().getArray(CONF_KEY_TOPICS, new JsonArray());
    for (int i = 0; i < topics.size(); i++) {
        JsonObject topicConfig = topics.get(i);
        m_topics.add(Topic.create(topicConfig));
    }

    //
    // Producer
    //
    NSQConfig nsqConfig = config.buildNSQConfig(variables());
    m_producer = new NSQProducer();
    m_producer.setConfig(nsqConfig);

    for (String host : nodes) {

        int port = NSQ_HTTP_PORT;
        int pos = host.lastIndexOf(":");

        if (pos != -1) {
            port = Integer.parseInt(host.substring(pos + 1));
            host = host.substring(0, pos);
        }

        m_producer.addAddress(host, port);
    }

    m_producer.start();
}