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.hypersocket.server.HypersocketServerImpl.java

License:Open Source License

public HypersocketServerImpl() {
    Security.addProvider(new BouncyCastleProvider());
    controllerPackages.add("com.hypersocket.json.**");
    controllerPackages.add("com.hypersocket.**.json");
}

From source file:com.ibm.iotf.client.AbstractClient.java

License:Open Source License

static SSLSocketFactory getSocketFactory(final String caCrtFile, final String crtFile, final String keyFile,
        final String password) throws IOException, KeyStoreException, NoSuchAlgorithmException,
        CertificateException, UnrecoverableKeyException, KeyManagementException {
    Security.addProvider(new BouncyCastleProvider());
    X509Certificate caCert = null;

    if (caCrtFile != null) {
        // load CA certificate
        PEMReader reader = new PEMReader(
                new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(caCrtFile)))));
        caCert = (X509Certificate) reader.readObject();
        reader.close();//from w ww  .  ja  va 2 s . co m
    } else {
        ClassLoader classLoader = AbstractClient.class.getClassLoader();
        PEMReader reader = new PEMReader(
                new InputStreamReader(classLoader.getResource(SERVER_MESSAGING_PEM).openStream()));
        caCert = (X509Certificate) reader.readObject();
        reader.close();
    }

    PEMReader reader = new PEMReader(
            new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(crtFile)))));
    X509Certificate cert = (X509Certificate) reader.readObject();
    reader.close();

    // load client private key
    reader = new PEMReader(
            new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(keyFile)))));
    KeyPair key = (KeyPair) reader.readObject();
    reader.close();

    TrustManagerFactory tmf = null;
    if (caCert != null) {
        // CA certificate is used to authenticate server
        KeyStore caKs = KeyStore.getInstance("JKS");
        //caKs.load(null, null);
        caKs.load(null, null);
        caKs.setCertificateEntry("ca-certificate", caCert);
        tmf = TrustManagerFactory.getInstance("PKIX");
        tmf.init(caKs);
    }
    // client key and certificates are sent to server so it can authenticate us
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);
    ks.setCertificateEntry("certificate", cert);
    ks.setKeyEntry("private-key", key.getPrivate(), password.toCharArray(),
            new java.security.cert.Certificate[] { cert });
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("PKIX");
    kmf.init(ks, password.toCharArray());

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

    return context.getSocketFactory();
}

From source file:com.indivica.olis.Driver.java

License:Open Source License

public static String signData(String data) {
    X509Certificate cert = null;/* w w  w . ja v a2s.  co m*/
    PrivateKey priv = null;
    KeyStore keystore = null;
    String pwd = "Olis2011";
    String result = null;
    try {
        Security.addProvider(new BouncyCastleProvider());

        keystore = KeyStore.getInstance("PKCS12", "SunJSSE");
        // Load the keystore
        keystore.load(new FileInputStream(OscarProperties.getInstance().getProperty("olis_keystore")),
                pwd.toCharArray());

        Enumeration e = keystore.aliases();
        String name = "";

        if (e != null) {
            while (e.hasMoreElements()) {
                String n = (String) e.nextElement();
                if (keystore.isKeyEntry(n)) {
                    name = n;
                }
            }
        }

        // Get the private key and the certificate
        priv = (PrivateKey) keystore.getKey(name, pwd.toCharArray());
        cert = (X509Certificate) keystore.getCertificate(name);

        // I'm not sure if this is necessary

        Certificate[] certChain = keystore.getCertificateChain(name);
        ArrayList<Certificate> certList = new ArrayList<Certificate>();
        certList.add(cert);
        CertStore certs = null;

        certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC");

        // Encrypt data
        CMSSignedDataGenerator sgen = new CMSSignedDataGenerator();

        // What digest algorithm i must use? SHA1? MD5? RSA?...
        DefaultSignedAttributeTableGenerator attributeGenerator = new DefaultSignedAttributeTableGenerator();
        sgen.addSigner(priv, cert, CMSSignedDataGenerator.DIGEST_SHA1, attributeGenerator, null);

        // I'm not sure this is necessary
        sgen.addCertificatesAndCRLs(certs);

        // I think that the 2nd parameter need to be false (detached form)
        CMSSignedData csd = sgen.generate(new CMSProcessableByteArray(data.getBytes()), true, "BC");

        byte[] signedData = csd.getEncoded();
        byte[] signedDataB64 = Base64.encode(signedData);

        result = new String(signedDataB64);

    } catch (Exception e) {
        MiscUtils.getLogger().error("Can't sign HL7 message for OLIS", e);
    }
    return result;
}

From source file:com.infinities.keystone4j.utils.Cms.java

License:Apache License

private String cmsSignData(String data, String signingCertFileName, String signingKeyFile, String outform)
        throws CertificateException, IOException, NoSuchAlgorithmException, NoSuchProviderException,
        CMSException, OperatorCreationException, CertStoreException {
    if (Strings.isNullOrEmpty(outform)) {
        outform = PKI_ASN1_FORM;//w  w w  .j a va  2 s  .co m
    }

    Security.addProvider(new BouncyCastleProvider());
    CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
    logger.debug("signingCertFile: {}, caFile:{}", new Object[] { signingCertFileName, signingKeyFile });
    X509Certificate signercert = generateCertificate(signingCertFileName);
    // X509Certificate cacert = generateCertificate(caFileName);
    PrivateKey key = generatePrivateKey(signingKeyFile);
    ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(key);
    gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(
            new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()).build(sha1Signer, signercert));
    List<X509Certificate> certList = new ArrayList<X509Certificate>();
    certList.add(signercert);
    Store certs = new JcaCertStore(certList);
    gen.addCertificates(certs);

    CMSProcessableByteArray b = new CMSProcessableByteArray(data.getBytes());
    CMSSignedData signed = gen.generate(b, true);
    String signedContent = new String(DERtoPEM(signed.getContentInfo().getDEREncoded(), "CMS"));
    return signedContent;
}

From source file:com.infinities.keystone4j.utils.Cms.java

License:Apache License

@SuppressWarnings("rawtypes")
public String verifySignature(byte[] sigbytes, String signingCertFileName, String caFileName)
        throws CMSException, CertificateException, OperatorCreationException, NoSuchAlgorithmException,
        NoSuchProviderException, CertPathBuilderException, InvalidAlgorithmParameterException, IOException,
        CertificateVerificationException {
    logger.debug("signingCertFile: {}, caFile:{}", new Object[] { signingCertFileName, caFileName });
    Security.addProvider(new BouncyCastleProvider());
    X509Certificate signercert = generateCertificate(signingCertFileName);
    X509Certificate cacert = generateCertificate(caFileName);
    Set<X509Certificate> additionalCerts = new HashSet<X509Certificate>();
    additionalCerts.add(cacert);/*from   ww w . j ava2s  .  c o  m*/

    CertificateVerifier.verifyCertificate(signercert, additionalCerts, true); // .validateKeyChain(signercert,
    // certs);
    if (Base64Verifier.isBase64(sigbytes)) {
        try {
            sigbytes = Base64.decode(sigbytes);
            logger.debug("Signature file is BASE64 encoded");
        } catch (Exception ioe) {
            logger.warn("Problem decoding from b64", ioe);
        }
    }

    // sigbytes = Base64.decode(sigbytes);

    // --- Use Bouncy Castle provider to verify included-content CSM/PKCS#7
    // signature ---
    ASN1InputStream in = null;
    try {
        logger.debug("sigbytes size: {}", sigbytes.length);
        in = new ASN1InputStream(new ByteArrayInputStream(sigbytes), Integer.MAX_VALUE);

        CMSSignedData s = new CMSSignedData(ContentInfo.getInstance(in.readObject()));
        Store store = s.getCertificates();
        SignerInformationStore signers = s.getSignerInfos();
        Collection c = signers.getSigners();
        Iterator it = c.iterator();
        int verified = 0;

        while (it.hasNext()) {
            X509Certificate cert = null;
            SignerInformation signer = (SignerInformation) it.next();
            Collection certCollection = store.getMatches(signer.getSID());
            if (certCollection.isEmpty() && signercert == null)
                continue;
            else if (signercert != null) // use a signer cert file for
                // verification, if it was
                // provided
                cert = signercert;
            else { // use the certificates included in the signature for
                   // verification
                Iterator certIt = certCollection.iterator();
                cert = (X509Certificate) certIt.next();
            }

            // if (signer.verify(new
            // JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert)))
            // verified++;
        }

        if (verified == 0) {
            logger.warn(" No signers' signatures could be verified !");
        } else if (signercert != null)
            logger.info("Verified a signature using signer certificate file  {}", signingCertFileName);
        else
            logger.info("Verified a signature using a certificate in the signature data");

        CMSProcessableByteArray cpb = (CMSProcessableByteArray) s.getSignedContent();
        byte[] rawcontent = (byte[]) cpb.getContent();

        return new String(rawcontent);
    } catch (Exception ex) {
        logger.error("Couldn't verify included-content CMS signature", ex);
        throw new RuntimeException("Couldn't verify included-content CMS signature", ex);
    } finally {
        if (in != null) {
            in.close();
        }
    }
}

From source file:com.infinities.skyport.util.KeyStoreCreator.java

License:Apache License

public KeyStore buildKeyStore(String keyStoreType, String pass, byte[] content, String alias)
        throws IOException {
    InputStream inputStream = null;
    try {//from   www  .j av a 2  s  .c o m
        Security.addProvider(new BouncyCastleProvider());
        KeyStore ks = KeyStore.getInstance(keyStoreType, BouncyCastleProvider.PROVIDER_NAME);
        char[] password = pass.toCharArray();
        inputStream = new ByteArrayInputStream(content);
        ks.load(inputStream, password);
        logger.debug("Certificate entry has been added to the keystore");

        return ks;
    } catch (Exception e) {
        throw new IOException("Error while importing a trusted certificate with alias: " + alias, e);
    }
}

From source file:com.intuit.autumn.crypto.AlgorithmEncryptor.java

License:Apache License

/**
 * Constructor accepting injectable configurables.
 *
 * @param key       the key to be used by the configured implementation
 * @param algorithm the configured cryptography algorithm
 * @param poolSize  the configured cryptography implementation pool size
 *//*from  w w  w  . j av a  2  s  . c  o m*/

@Inject
public AlgorithmEncryptor(@Named("crypto.key") final String key,
        @Named("crypto.algorithm") final String algorithm, @Named("crypto.poolsize") final int poolSize) {
    encryptor = new PooledPBEStringEncryptor();

    addProvider(new BouncyCastleProvider());

    encryptor.setProvider(new BouncyCastleProvider());
    encryptor.setAlgorithm(algorithm);
    encryptor.setPoolSize(poolSize);
    encryptor.setPassword(key);
}

From source file:com.intuit.tank.jenkins.proxy.ProxyWrapper.java

License:Open Source License

private void initializeProxy() {
    Security.addProvider(new BouncyCastleProvider());

    File certAuthority = new File(workspacePath + "/auto_generated_ca.p12");

    if (!certAuthority.exists()) {
        generateCertificate(certAuthority);
    }/*  ww w  .  j  a va 2  s  .  c  om*/

    File tankScript = new File(workspacePath + "/tank-script.xml");
    if (tankScript.exists()) {
        LogPrinter.print("Tank Script found in workspace, deleting", logger);
        boolean deleted = tankScript.delete();
        LogPrinter.print("Tank Script Deleted? " + deleted, logger);
    }

    FixedProxyConfiguration config = new FixedProxyConfiguration(proxyPort, tankScript.getAbsolutePath());
    config.setCertificateAuthorityPath(certAuthority.getAbsolutePath());
    this.config = config;
    proxy = new EmbeddedProxy(config);
}

From source file:com.intuit.tank.proxy.ProxyApp.java

License:Open Source License

public static void main(String[] args) {
    if (StringUtils.isBlank(System.getProperty("jsse.enableSNIExtension"))) {
        System.setProperty("jsse.enableSNIExtension", "false");
    }//  w  w  w .j  a v a 2s.c  om
    if (StringUtils.isBlank(System.getProperty("https.protocols"))) {
        System.setProperty("https.protocols", "TLSv1,SSLv3");
    }
    Security.addProvider(new BouncyCastleProvider()); // add it
    new ProxyApp();
}

From source file:com.itextpdf.samples.signatures.chapter02.C2_06_SignatureAppearance.java

public static void main(String[] args) throws IOException, GeneralSecurityException {
    BouncyCastleProvider provider = new BouncyCastleProvider();
    Security.addProvider(provider);
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(new FileInputStream(KEYSTORE), PASSWORD);
    String alias = ks.aliases().nextElement();
    PrivateKey pk = (PrivateKey) ks.getKey(alias, PASSWORD);
    Certificate[] chain = ks.getCertificateChain(alias);
    C2_06_SignatureAppearance app = new C2_06_SignatureAppearance();
    app.sign1(SRC, "Signature1", String.format(DEST, 1), chain, pk, DigestAlgorithms.SHA256, provider.getName(),
            PdfSigner.CryptoStandard.CMS, "Custom appearance example", "Ghent");
    app.sign2(SRC, "Signature1", String.format(DEST, 2), chain, pk, DigestAlgorithms.SHA256, provider.getName(),
            PdfSigner.CryptoStandard.CMS, "Custom appearance example", "Ghent");
    app.sign3(SRC, "Signature1", String.format(DEST, 3), chain, pk, DigestAlgorithms.SHA256, provider.getName(),
            PdfSigner.CryptoStandard.CMS, "Custom appearance example", "Ghent");
    app.sign4(SRC, "Signature1", String.format(DEST, 4), chain, pk, DigestAlgorithms.SHA256, provider.getName(),
            PdfSigner.CryptoStandard.CMS, "Custom appearance example", "Ghent");
}