Search in sources :

Example 31 with BouncyCastleProvider

use of org.bouncycastle.jce.provider.BouncyCastleProvider in project tomee by apache.

the class HttpsConnectionTest method createKeyStore.

private File createKeyStore() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    dropKeyStore();
    File keyStore = new File(STORE_PATH);
    keyStore.getParentFile().mkdirs();
    try (final FileOutputStream fos = new FileOutputStream(keyStore)) {
        final KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("RSA");
        keyGenerator.initialize(1024);
        final KeyPair pair = keyGenerator.generateKeyPair();
        final boolean addBc = Security.getProvider("BC") == null;
        if (addBc) {
            Security.addProvider(new BouncyCastleProvider());
        }
        try {
            final X509v1CertificateBuilder x509v1CertificateBuilder = new JcaX509v1CertificateBuilder(new X500Name("cn=" + SERVER), BigInteger.valueOf(1), new Date(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(1)), new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(1)), new X500Name("cn=" + SERVER), pair.getPublic());
            final X509CertificateHolder certHldr = x509v1CertificateBuilder.build(new JcaContentSignerBuilder("SHA1WithRSA").setProvider("BC").build(pair.getPrivate()));
            final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certHldr);
            final KeyStore ks = KeyStore.getInstance("JKS");
            ks.load(null, STORE_PWD.toCharArray());
            ks.setKeyEntry(SERVER, pair.getPrivate(), STORE_PWD.toCharArray(), new Certificate[] { cert });
            ks.store(fos, STORE_PWD.toCharArray());
        } finally {
            if (addBc) {
                Security.removeProvider("BC");
            }
        }
    } catch (final Exception e) {
        Assert.fail(e.getMessage());
    }
    return keyStore;
}
Also used : KeyPair(java.security.KeyPair) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) KeyPairGenerator(java.security.KeyPairGenerator) X500Name(org.bouncycastle.asn1.x500.X500Name) KeyStore(java.security.KeyStore) JcaX509v1CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v1CertificateBuilder) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) InvocationTargetException(java.lang.reflect.InvocationTargetException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) FileOutputStream(java.io.FileOutputStream) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) X509v1CertificateBuilder(org.bouncycastle.cert.X509v1CertificateBuilder) JcaX509v1CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v1CertificateBuilder) File(java.io.File) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 32 with BouncyCastleProvider

use of org.bouncycastle.jce.provider.BouncyCastleProvider in project sic by belluccifranco.

the class AfipWebServiceSOAPClient method crearCMS.

public byte[] crearCMS(byte[] p12file, String p12pass, String signer, String service, long ticketTime) {
    PrivateKey pKey = null;
    X509Certificate pCertificate = null;
    byte[] asn1_cms = null;
    CertStore cstore = null;
    try {
        KeyStore ks = KeyStore.getInstance("pkcs12");
        InputStream is;
        is = Utilidades.convertirByteArrayToInputStream(p12file);
        ks.load(is, p12pass.toCharArray());
        is.close();
        pKey = (PrivateKey) ks.getKey(signer, p12pass.toCharArray());
        pCertificate = (X509Certificate) ks.getCertificate(signer);
        ArrayList<X509Certificate> certList = new ArrayList<>();
        certList.add(pCertificate);
        if (Security.getProvider("BC") == null) {
            Security.addProvider(new BouncyCastleProvider());
        }
        cstore = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC");
    } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException | UnrecoverableKeyException | InvalidAlgorithmParameterException | NoSuchProviderException ex) {
        LOGGER.error(ex.getMessage());
        throw new BusinessServiceException(ResourceBundle.getBundle("Mensajes").getString("mensaje_certificado_error"));
    }
    String loginTicketRequest_xml = this.crearTicketRequerimientoAcceso(service, ticketTime);
    try {
        CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
        generator.addSigner(pKey, pCertificate, CMSSignedDataGenerator.DIGEST_SHA1);
        generator.addCertificatesAndCRLs(cstore);
        CMSProcessable data = new CMSProcessableByteArray(loginTicketRequest_xml.getBytes());
        CMSSignedData signed = generator.generate(data, true, "BC");
        asn1_cms = signed.getEncoded();
    } catch (IllegalArgumentException | CertStoreException | CMSException | NoSuchAlgorithmException | NoSuchProviderException | IOException ex) {
        LOGGER.error(ex.getMessage());
        throw new BusinessServiceException(ResourceBundle.getBundle("Mensajes").getString("mensaje_firmando_certificado_error"));
    }
    return asn1_cms;
}
Also used : CMSSignedDataGenerator(org.bouncycastle.cms.CMSSignedDataGenerator) PrivateKey(java.security.PrivateKey) ArrayList(java.util.ArrayList) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CollectionCertStoreParameters(java.security.cert.CollectionCertStoreParameters) BusinessServiceException(sic.service.BusinessServiceException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) CMSProcessableByteArray(org.bouncycastle.cms.CMSProcessableByteArray) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) InputStream(java.io.InputStream) CertStoreException(java.security.cert.CertStoreException) KeyStoreException(java.security.KeyStoreException) IOException(java.io.IOException) KeyStore(java.security.KeyStore) CMSSignedData(org.bouncycastle.cms.CMSSignedData) X509Certificate(java.security.cert.X509Certificate) CMSProcessable(org.bouncycastle.cms.CMSProcessable) NoSuchProviderException(java.security.NoSuchProviderException) CertStore(java.security.cert.CertStore) CMSException(org.bouncycastle.cms.CMSException)

Example 33 with BouncyCastleProvider

use of org.bouncycastle.jce.provider.BouncyCastleProvider in project bitsquare by bitsquare.

the class EncryptionTest method setup.

@Before
public void setup() throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException, CryptoException {
    Security.addProvider(new BouncyCastleProvider());
    dir = File.createTempFile("temp_tests", "");
    dir.delete();
    dir.mkdir();
    KeyStorage keyStorage = new KeyStorage(dir);
    keyRing = new KeyRing(keyStorage);
}
Also used : BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) Before(org.junit.Before)

Example 34 with BouncyCastleProvider

use of org.bouncycastle.jce.provider.BouncyCastleProvider in project bitsquare by bitsquare.

the class StressTestMailboxMessage method setUp.

// # TEST SETUP
@Before
public void setUp() throws Exception {
    // Parse test parameter environment variables.
    /** Number of peer nodes to create. */
    final int nPeers = parseEnvInt(NPEERS_ENVVAR, NPEERS_DEFAULT, NPEERS_MIN);
    directCount = parseEnvInt(DIRECT_COUNT_ENVVAR, DIRECT_COUNT_DEFAULT, 0);
    mailboxCount = parseEnvInt(MAILBOX_COUNT_ENVVAR, MAILBOX_COUNT_DEFAULT, 0);
    /** A property where threads can indicate setup failure of local services (Tor node, hidden service). */
    final BooleanProperty localServicesFailed = new SimpleBooleanProperty(false);
    /** A barrier to wait for concurrent setup of local services (Tor node, hidden service). */
    final CountDownLatch localServicesLatch = new CountDownLatch(1 + /*seed node*/
    nPeers);
    /* A barrier to wait for concurrent reception of preliminary data in peers. */
    final CountDownLatch prelimDataLatch = new CountDownLatch(nPeers);
    /* A barrier to wait for concurrent bootstrap of peers. */
    final CountDownLatch bootstrapLatch = new CountDownLatch(nPeers);
    // Set a security provider to allow key generation.
    Security.addProvider(new BouncyCastleProvider());
    // Create the test data directory.
    testDataDir = createTestDataDirectory();
    print("test data directory: " + testDataDir);
    // Setting the executor seems to make tests more stable against ``ConcurrentModificationException``
    // (see #443).  However it make it use more open files, so you may need to use ``ulimit -n NUMBER``
    // or run ``prlimit -nNUMBER -pPID`` (as root) on your shell's PID if you get too many open files errors.
    // NUMBER=16384 seems to be enough for 100 peers in Debian GNU/Linux.
    UserThread.setExecutor(Executors.newSingleThreadExecutor());
    // Create and start the seed node.
    seedNode = new DummySeedNode(testDataDir.toString());
    final NodeAddress seedNodeAddress = newSeedNodeAddress();
    useLocalhost = seedNodeAddress.hostName.equals("localhost");
    final Set<NodeAddress> seedNodes = new HashSet<>(1);
    // the only seed node in tests
    seedNodes.add(seedNodeAddress);
    seedNode.createAndStartP2PService(seedNodeAddress, DummySeedNode.MAX_CONNECTIONS_DEFAULT, useLocalhost, REGTEST_NETWORK_ID, USE_DETAILED_LOGGING, seedNodes, new SeedServiceListener(localServicesLatch, localServicesFailed));
    print("created seed node");
    // Create and start peer nodes, all connecting to the seed node above.
    if (useLocalhost) {
        seedNodesRepository.setLocalhostSeedNodeAddresses(seedNodes);
    } else {
        seedNodesRepository.setTorSeedNodeAddresses(seedNodes);
    }
    for (int p = 0; p < nPeers; p++) {
        // peer network port
        final int peerPort = Utils.findFreeSystemPort();
        peerPorts.add(peerPort);
        // create, save and start peer
        final P2PService peer = createPeerNode(p, peerPort);
        //noinspection ConstantConditions
        peerPKRings.add(peer.getKeyRing().getPubKeyRing());
        peerNodes.add(peer);
        peer.start(new PeerServiceListener(localServicesLatch, localServicesFailed, prelimDataLatch, bootstrapLatch));
    }
    print("created peer nodes");
    // Wait for concurrent tasks to finish.
    localServicesLatch.await();
    // Check if any node reported setup failure on start.
    if (localServicesFailed.get()) {
        throw new Exception("nodes failed to start");
    }
    print("all local nodes started");
    // Wait for peers to get their preliminary data.
    assertLatch("timed out while waiting for preliminary data", prelimDataLatch, MAX_PRELIMINARY_DELAY_SECS * nPeers, TimeUnit.SECONDS);
    print("preliminary data received");
    // Wait for peers to complete their bootstrapping.
    assertLatch("timed out while waiting for bootstrap", bootstrapLatch, MAX_BOOTSTRAP_DELAY_SECS * nPeers, TimeUnit.SECONDS);
    print("bootstrap complete");
}
Also used : SimpleBooleanProperty(javafx.beans.property.SimpleBooleanProperty) BooleanProperty(javafx.beans.property.BooleanProperty) SimpleBooleanProperty(javafx.beans.property.SimpleBooleanProperty) CountDownLatch(java.util.concurrent.CountDownLatch) IOException(java.io.IOException) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) Before(org.junit.Before)

Aggregations

BouncyCastleProvider (org.bouncycastle.jce.provider.BouncyCastleProvider)34 IOException (java.io.IOException)12 KeyPair (java.security.KeyPair)9 X509Certificate (java.security.cert.X509Certificate)9 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)8 KeyPairGenerator (java.security.KeyPairGenerator)6 KeyStore (java.security.KeyStore)6 SecureRandom (java.security.SecureRandom)5 Date (java.util.Date)5 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)5 File (java.io.File)4 FileOutputStream (java.io.FileOutputStream)4 SecretKey (javax.crypto.SecretKey)4 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)4 Before (org.junit.Before)4 KeyStoreException (java.security.KeyStoreException)3 NoSuchProviderException (java.security.NoSuchProviderException)3 CertificateException (java.security.cert.CertificateException)3 X500Name (org.bouncycastle.asn1.x500.X500Name)3 Test (org.junit.Test)3