Bouncy Castle Java Distribution (Mirror)

Overview

The Bouncy Castle Crypto Package For Java

Build Status

The Bouncy Castle Crypto package is a Java implementation of cryptographic algorithms, it was developed by the Legion of the Bouncy Castle, a registered Australian Charity, with a little help! The Legion, and the latest goings on with this package, can be found at https://www.bouncycastle.org.

The Legion also gratefully acknowledges the contributions made to this package by others (see here for the current list). If you would like to contribute to our efforts please feel free to get in touch with us or visit our donations page, sponsor some specific work, or purchase a support contract through Crypto Workshop.

The package is organised so that it contains a light-weight API suitable for use in any environment (including the newly released J2ME) with the additional infrastructure to conform the algorithms to the JCE framework.

Except where otherwise stated, this software is distributed under a license based on the MIT X Consortium license. To view the license, see here. The OpenPGP library also includes a modified BZIP2 library which is licensed under the Apache Software License, Version 2.0.

Note: this source tree is not the FIPS version of the APIs - if you are interested in our FIPS version please contact us directly at [email protected].

Code Organisation

The clean room JCE, for use with JDK 1.1 to JDK 1.3 is in the jce/src/main/java directory. From JDK 1.4 and later the JCE ships with the JVM, the source for later JDKs follows the progress that was made in the later versions of the JCE. If you are using a later version of the JDK which comes with a JCE install please do not include the jce directory as a source file as it will clash with the JCE API installed with your JDK.

The core module provides all the functionality in the ligthweight APIs.

The prov module provides all the JCA/JCE provider functionality.

The pkix module is the home for code for X.509 certificate generation and the APIs for standards that rely on ASN.1 such as CMS, TSP, PKCS#12, OCSP, CRMF, and CMP.

The mail module provides an S/MIME API built on top of CMS.

The pg module is the home for code used to support OpenPGP.

The tls module is the home for code used to a general TLS API and JSSE Provider.

The build scripts that come with the full distribution allow creation of the different releases by using the different source trees while excluding classes that are not appropriate and copying in the required compatibility classes from the directories containing compatibility classes appropriate for the distribution.

If you want to try create a build for yourself, using your own environment, the best way to do it is to start with the build for the distribution you are interested in, make sure that builds, and then modify your build scripts to do the required exclusions and file copies for your setup, otherwise you are likely to get class not found exceptions. The final caveat to this is that as the j2me distribution includes some compatibility classes starting in the java package, you need to use an obfuscator to change the package names before attempting to import a midlet using the BC API.

Examples and Tests

To view some examples, look at the test programs in the packages:

  • org.bouncycastle.crypto.test

  • org.bouncycastle.jce.provider.test

  • org.bouncycastle.cms.test

  • org.bouncycastle.mail.smime.test

  • org.bouncycastle.openpgp.test

  • org.bouncycastle.tsp.test

There are also some specific example programs for dealing with SMIME and OpenPGP. They can be found in:

  • org.bouncycastle.mail.smime.examples

  • org.bouncycastle.openpgp.examples

Mailing Lists

For those who are interested, there are 2 mailing lists for participation in this project. To subscribe use the links below and include the word subscribe in the message body. (To unsubscribe, replace subscribe with unsubscribe in the message body)

  • [email protected]
    This mailing list is for new release announcements only, general subscribers cannot post to it.
  • [email protected]
    This mailing list is for discussion of development of the package. This includes bugs, comments, requests for enhancements, questions about use or operation.

NOTE: You need to be subscribed to send mail to the above mailing list.

Feedback and Contributions

If you want to provide feedback directly to the members of The Legion then please use [email protected], if you want to help this project survive please consider donating.

For bug reporting/requests you can report issues here on github, or via feedback-crypto if required. We will accept pull requests based on this repository as well, but only on the basis that any code included may be distributed under the Bouncy Castle License.

Finally

Enjoy!

Comments
  • RFC4998 implementation error ?

    RFC4998 implementation error ?

    It seems that the current implementation of RFC4998 (Evidence Record Syntax) is incorrect. I maybe wrong in the way I use the ERSArchiveTimeStampGenerator class, but from what I see the reduced hash tree contains the hashes of all data elements that are provided. The RFC however states that only selected hash values should be included (cf. section 4.2) . Similarly, I can only obtain a single ERSEvidenceRecord for a given input of n data elements, whereas it should be a n to n mapping with all evidence records sharing the same TimestampToken but containing different reduced hashtrees. Any thoughts on this ?

    opened by veebee 44
  • Incompatible GCM - Version 1.71b07

    Incompatible GCM - Version 1.71b07

    Testing the jars for issue #1100 I was faced some incompatibility with other (d)tls libraries. My Eclipse/Californium Interoperability Test have succeeded with BC 1.70, but fail with the 1.71b07.

    • OpenSSL 1.1.1 11 Sep 2018
    • GnuTLS 3.5.18
    • MbedTLS 2.27.0

    Failing handshakes:

    openssl-client, bc-server: psk_gcm.pcapng.gz

    bc-client, openssl-server: server_psk_gcm.pcapng.gz

    For me the captures shows, that the GCM MAC is calculated wrong. Next step from my side would be a test, which compares the output of SunJCE GCM with BC. I hope, that makes nailing down the problem easier.

    opened by boaks 38
  • Encrypt data with Asymmetric Public key ECGOST3410-2012

    Encrypt data with Asymmetric Public key ECGOST3410-2012

    Method for encryptData:

        public static byte[] encryptData(byte[] data, X509Certificate encryptionCertificate)
    		throws CertificateEncodingException, CMSException, IOException, NoSuchAlgorithmException,
    		NoSuchProviderException {
    	byte[] encryptedData = null;
    	if (null != data && null != encryptionCertificate) {
    		CMSEnvelopedDataGenerator cmsEnvelopedDataGenerator = new CMSEnvelopedDataGenerator();
    		
    		JceKeyTransRecipientInfoGenerator jceKey = new JceKeyTransRecipientInfoGenerator(encryptionCertificate).setProvider("BC");
    		cmsEnvelopedDataGenerator.addRecipientInfoGenerator(jceKey);
    		CMSTypedData msg = new CMSProcessableByteArray(data);
    		OutputEncryptor encryptor = new JceCMSContentEncryptorBuilder(CMSAlgorithm.GOST28147_GCFB).setProvider("BC").build();
    		CMSEnvelopedData cmsEnvelopedData = cmsEnvelopedDataGenerator.generate(msg, encryptor);
    		encryptedData = cmsEnvelopedData.getEncoded();
    	}
    	return encryptedData;
    }
    
    
    
    Exception in thread "main" org.bouncycastle.cms.CMSException: exception wrapping content key: cannot create cipher: No such algorithm: 1.2.643.7.1.1.1.2
    at org.bouncycastle.cms.KeyTransRecipientInfoGenerator.generate(KeyTransRecipientInfoGenerator.java:42)
    at org.bouncycastle.cms.CMSEnvelopedDataGenerator.doGenerate(CMSEnvelopedDataGenerator.java:94)
    at org.bouncycastle.cms.CMSEnvelopedDataGenerator.generate(CMSEnvelopedDataGenerator.java:129)
    at com.joymoney.parameter.Boc.encryptData(Boc.java:188)
    at com.joymoney.parameter.Boc.main(Boc.java:109)
    Caused by: org.bouncycastle.operator.OperatorCreationException: cannot create cipher: No such algorithm: 1.2.643.7.1.1.1.2
    at org.bouncycastle.operator.jcajce.OperatorHelper.createAsymmetricWrapper(OperatorHelper.java:201)
    at org.bouncycastle.operator.jcajce.JceAsymmetricKeyWrapper.generateWrappedKey(JceAsymmetricKeyWrapper.java:127)
    at org.bouncycastle.cms.KeyTransRecipientInfoGenerator.generate(KeyTransRecipientInfoGenerator.java:38)
    ... 4 more
    

    Could anybody help me? How to do it?

    MyTestCert test.txt

    opened by nurlanarysbaev 37
  • bad_record_mac error as a cause of service rollout restart

    bad_record_mac error as a cause of service rollout restart

    Hi, One of our services implementing Bouncy Castle dependency constantly falls into rollout restart (this service with no Bouncy Castle works normally). What can be seen is in logs is:

    redis.clients.jedis.exceptions.JedisConnectionException: org.bouncycastle.tls.TlsFatalAlert: bad_record_mac(20) at redis.clients.jedis.util.RedisInputStream.ensureFill(RedisInputStream.java:208) at redis.clients.jedis.util.RedisInputStream.readByte(RedisInputStream.java:46) at redis.clients.jedis.Protocol.process(Protocol.java:126)

    (...)
    

    Caused by: javax.crypto.AEADBadTagException: Error finalising cipher data: mac check in GCM failed at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:77) at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499) at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480) at org.bouncycastle.jcajce.provider.ClassUtil.throwBadTagException(Unknown Source) at org.bouncycastle.jcajce.provider.BaseCipher.engineDoFinal(Unknown Source) at org.bouncycastle.jcajce.provider.BaseCipher.engineDoFinal(Unknown Source) at java.base/javax.crypto.Cipher.doFinal(Cipher.java:2417) at org.bouncycastle.tls.crypto.impl.jcajce.JceAEADCipherImpl.doFinal(JceAEADCipherImpl.java:135)

    Current Bouncy Castle version is: 1.0.12.3 The issue can be seen only on one of our evironments. On the other service operates normally. I noticed that on the issued environment the traffic is much bigger than on the others. I've read somewhere, that: "bad_record_mac could mean some sort of packet corruption on-the-wire, but it's not common in practice (...) it happens with a probability of one in tens of millions" Taking this into consideration, is it possible that huge traffic is the cause of those bad_record_mac(20) errors which cause service rollout restart? If so, what could be possible solution for this situation? Is there a safe 'treshold' for the throughput to avoid these problems? Thanks in advance for your help

    opened by Niegi 31
  • Java 13 (I know...) Compatibility - XDH Key Generation (Works on Java 12)

    Java 13 (I know...) Compatibility - XDH Key Generation (Works on Java 12)

    I am not sure if this has anything to do with Bouncycastle. Java 13 has JEP 353 which rewrites (parts) of the legacy socket API. I am using Bouncycastle 1.62.

    When I try to connect to Amazon AWS DynamoDB on Java 13, I get the following (partial) stack trace:

    Caused by: java.lang.RuntimeException: Could not generate XDH keypair
    at java.base/sun.security.ssl.XDHKeyExchange$XDHEPossession.<init>(XDHKeyExchange.java:110)
    at java.base/sun.security.ssl.NamedGroup$XDHFunctions.createPossession(NamedGroup.java:750)
    at java.base/sun.security.ssl.NamedGroup.createPossession(NamedGroup.java:390)
    at java.base/sun.security.ssl.SSLKeyExchange$T13KeyAgreement.createPossession(SSLKeyExchange.java:568)
    at java.base/sun.security.ssl.SSLKeyExchange.createPossessions(SSLKeyExchange.java:84)
    at java.base/sun.security.ssl.KeyShareExtension$CHKeyShareProducer.produce(KeyShareExtension.java:255)
    at java.base/sun.security.ssl.SSLExtension.produce(SSLExtension.java:571)
    at java.base/sun.security.ssl.SSLExtensions.produce(SSLExtensions.java:250)
    at java.base/sun.security.ssl.ClientHello$ClientHelloKickstartProducer.produce(ClientHello.java:649)
    at java.base/sun.security.ssl.SSLHandshake.kickstart(SSLHandshake.java:519)
    at java.base/sun.security.ssl.ClientHandshakeContext.kickstart(ClientHandshakeContext.java:107)
    at java.base/sun.security.ssl.TransportContext.kickstart(TransportContext.java:231)
    at java.base/sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:430)
    ... 61 more
    Caused by: java.security.InvalidAlgorithmParameterException: invalid parameterSpec: java.security.spec.NamedParameterSpec@15e0fe05
    at org.bouncycastle.jcajce.provider.asymmetric.edec.KeyPairGeneratorSpi.initialize(Unknown Source)
    at java.base/java.security.KeyPairGenerator$Delegate.initialize(KeyPairGenerator.java:699)
    at java.base/sun.security.ssl.XDHKeyExchange$XDHEPossession.<init>(XDHKeyExchange.java:105)
    ... 73 more
    

    Downgrading to the latest nightly build of the Java 12 repository makes the error go away.

    The actual chain of events here is that the Amazon AWS SDK is calling Apache's HTTP client which is trying to make an SSL connection. I am not 100% sure how Bouncycastle comes into it unless the only XDH provider accessible is Bouncycastle? I tried to put the provider at position 2, but it made no difference.

    I believe the full stack trace where a custom AWS Lambda runtime calls a Lambda request handler, calls DynamoDB, calls Apache, calls, etc. etc. is essentially obfuscation. I think this would show up trying to make an SSL connection to Amazon's DynamoDB server that happens to use XDH key exchange. I see some changes to the sun.security.ssl.SSLSocketImpl classes (as well as other classes in the stack trace) new to Java 13 (most likely related to the aforementioned JEP).

    This could very well be a bug in the new Java socket implementation and if so I will certainly open this upstream.

    Thanks for your time.

    opened by brcolow 30
  • CMSAuthEnvelopedData and CMSAuthEnvelopedGenerator java classes have only package access

    CMSAuthEnvelopedData and CMSAuthEnvelopedGenerator java classes have only package access

    The two java files CMSAuthEnvelopedData and CMSAuthEnvelopedGenerator have only package access and it seems the implementation is not finished yet. Background is I need to create a 1.2.840.113549.1.9.16.1.23 authEnvelopedData ASN1 structure and I tried to solve this with bouncycastle but the two classes are not really available for usage.

    opened by wolftobias 30
  • BDSA-2018-5235 raised for bouncycastle 1.6.8

    BDSA-2018-5235 raised for bouncycastle 1.6.8

    https://fis.blackducksoftware.com/api/vulnerabilities/BDSA-2018-5235/overview Bouncy Castle contains a weak key-hash message authentication code (HMAC) that is only 16 bits long which can result in hash collisions. This is due to an error within the BKS version 1 keystore (BKS-V1) files and could lead to an attacker being able to affect the integrity of these files.

    Note: This issue issue occurs due to functionality that was re-introduced following the fix for CVE-2018-5382 (BDSA-2018-1190).

    opened by erezul 29
  • org.bouncycastle.util.encoders.DecoderException: unable to decode base64 string: invalid characters encountered in base64 data

    org.bouncycastle.util.encoders.DecoderException: unable to decode base64 string: invalid characters encountered in base64 data

    Hello All,

    Could you please help me figure out the cause of the exception? In my project I've updated version of Bouncy Castle: from bcprov-jdk16-146.jar to bcprov-jdk15on-1.57.jar And now in my integration test I get an exception: org.bouncycastle.util.encoders.DecoderException: unable to decode base64 string: invalid characters encountered in base64 data at org.bouncycastle.util.encoders.Base64.decode(Unknown Source) at com.project.isx.server.AuthenticationTicket.<init>(AuthenticationTicket.java:570) at com.project.isx.server.AuthenticationTicket.readTicket(AuthenticationTicket.java:388) at com.project.isx.server.ResourceProcessor.init(ResourceProcessor.java:218) at com.project.isx.server.Processor.createResourceProcessor(Processor.java:756) at com.project.isx.server.Processor.process(Processor.java:622) at com.project.isx.server.AccessGateway.service(AccessGateway.java:134) at com.project.test.isx.server.resource.enrollment.TestNGPinSelfService.send(TestNGPinSelfService.java:174) at com.project.test.isx.server.resource.enrollment.TestNGPinSelfService._testPinSelfService(TestNGPinSelfService.java:148) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at org.testng.TestNG.run(TestNG.java:1064) at com.project.runtests.TestNGContainerSuite.run(TestNGContainerSuite.java:379) Caused by: java.io.IOException: invalid characters encountered in base64 data at org.bouncycastle.util.encoders.Base64Encoder.decode(Unknown Source) ... 31 more

    Maybe I need to update the another .jar because of the BC has some dependencies? Thanks!

    Best regards, Iryna

    opened by IrynaZhumatiy 27
  • Performance problems using BC 1.61

    Performance problems using BC 1.61

    Hi,

    I'm working on a project where we're developing some kind of TLS proxy that serves as a TLS endpoint and forwards the plaintext messages to a backend system. The private key cryptography is done within a HSM. For the public key operations we currently use Bouncycastle. For some use cases we expect up to 600 new connections per second, for each of which we have to perform a handshake. However, our benchmarks have shown that we do not reach this value by far (currently we are at about 90 handshakes/second). After analyzing the code using a profiler, we found that most of the time is spent inside Bouncycastle's JCA provider. For testing purposes we did the same benchmarks with the Sun provider and an OpenSSL JCA wrapper and got better results. With the Sun Provider we achieved about 150 handshakes/second and with the OpenSSL wrapper even 500.

    During the analysis we noticed that the slowest parts of the handshake are the encoding/decoding of certificates in DER format and the chain validation or more precisely the signature checks.

    Both the clients and the server use elliptic curves. The hot spot view of the profiler shows that most of the time is spent within the ECFieldElement class.

    The total duration of a handshake where client and server run on the same machine is 477 ms with Bouncycastle, 184 ms with Sun, and 12 ms with the OpenSSL wrapper.

    Is this difference to be expected? Are there published benchmarks regarding the performance of Bouncycastle? Is there anything I can do to improve performance, such as using certain settings?

    Best regards,

    Florian

    opened by PythEsc 23
  • Implementation of Timestamp Renewal and Hash-Tree Renewal for RFC 4998 (Evidence Record Syntax) missing(?)

    Implementation of Timestamp Renewal and Hash-Tree Renewal for RFC 4998 (Evidence Record Syntax) missing(?)

    I cannot find any (high-level) implementation and/or tests for Timestamp Renewal and Hash-Tree Renewal as defined in RFC 4998 5.2.. Did I miss that or is it actually missing?

    opened by raubv0gel 22
  • Performance - KeyPairGenerator - EC

    Performance - KeyPairGenerator - EC

    Bouncy Castle - bcprov-jdk15on - 1.70

    I tried to analyze a left over in the open source project Eclipse/Californium from last year Long loading time for class XECDHECryptography.

    Californium checks on startup, if a list of curves is supported by the JCE. Therefore it mainly generates a EC keypair for the provided curves. With SunEC that takes time, but we didn't receive complaints about that. BC takes much longer, it seems, especially on some android systems. There up to 10s have been reported.

    try {
    	String algo = "secp256r1";
    	long times[] = new long[3];
    	long start = System.nanoTime();
    	KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC", provider);
    	times[0] = System.nanoTime() - start;
    	ECGenParameterSpec genParams = new ECGenParameterSpec(algo);
    	keyPairGenerator.initialize(genParams, random);
    	times[1] = System.nanoTime() - start;
    	keyPairGenerator.generateKeyPair().getPublic();
    	times[2] = System.nanoTime() - start;
    	System.out.format("%18s %s: %10d%n", provider.toString(), algo, times[2]);
    	System.out.format("   %10d %10d%n", times[0], times[1]);
    } catch (InvalidAlgorithmParameterException ex) {
    	ex.printStackTrace();
    } catch (NoSuchAlgorithmException ex) {
    	ex.printStackTrace();
    }
    

    My times on ubuntu/java8:

    SunEC version 1.8 secp256r1:   17260094
            59473     357506
        BC version 1.7 secp256r1:  197245461
         12276845  178087941
        BC version 1.7 secp256r1:    1900402
            13105      51357
    

    I read a lot of comments in stackoverflow or similar platforms, about the SecureRandom. What makes me struggling: It seems, that this affects only the first time when such a key pair is constructed. A new SecureRandom is still fast for the second time a ec key pair is created.

    1. is there a way to speed up also the first time a key pair is created?
    2. is experience with android available?
    opened by boaks 22
  • bctls-fips:1.0.14 is fails socket write error with windows server and windows wsl

    bctls-fips:1.0.14 is fails socket write error with windows server and windows wsl

    package com.veracode.fips;
    
    import nl.altindag.ssl.SSLFactory;
    import nl.altindag.ssl.util.Apache5SslUtils;
    import org.apache.hc.client5.http.classic.methods.HttpGet;
    import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
    import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
    import org.apache.hc.client5.http.impl.classic.HttpClients;
    import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
    import org.apache.hc.client5.http.io.HttpClientConnectionManager;
    import org.apache.hc.client5.http.socket.LayeredConnectionSocketFactory;
    import org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider;
    import org.bouncycastle.jsse.provider.BouncyCastleJsseProvider;
    import org.bouncycastle.jsse.util.CustomSSLSocketFactory;
    import org.bouncycastle.tls.TlsFatalAlertReceived;
    
    import javax.net.ssl.*;
    import java.net.Socket;
    import java.net.URL;
    import java.util.Collections;
    import java.util.List;
    
    import static java.util.Objects.nonNull;
    import static org.apache.hc.core5.http.HttpHeaders.USER_AGENT;
    
    /**
     * Hello world!
     */
    public class App {
        public static void main(String[] args) {
            final var urls = List
                    .of("https://marketplace.vmware.com", "https://aws.amazon.com");
    
            for (final var url : urls) {
                try {
                    testWithSNIHostName(url);
                    testWithoutSNIHostNameApache(url);
                } catch (Exception e) {
                    System.out.println(e);
                }
            }
        }
    
    
        public static void testWithSNIHostName(String urlString) throws Exception {
            URL url = new URL(urlString);
            final SSLFactory sslFactory = sslFactory(true);
    
            SSLContext context = sslFactory.getSslContext();
            System.out.println("Created  sslFactory");
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            connection.setSSLSocketFactory(context.getSocketFactory());
            connection.setSSLSocketFactory(new CustomSSLSocketFactory(context.getSocketFactory()) {
                @Override
                protected Socket configureSocket(Socket s) {
                    SSLParameters sslParams = new SSLParameters();
                    sslParams.setServerNames(
                            Collections.<SNIServerName>singletonList(new SNIHostName(url.getHost())));
                    ((SSLSocket) s).setSSLParameters(sslParams);
                    return s;
                }
            });
            connection.setInstanceFollowRedirects(false);
            connection.setHostnameVerifier((ss, sslSession) -> true);
            System.out.println("Connection started" + urlString);
            connection.connect();
            System.out.println("Connected " + urlString);
        }
        
    
    
        public static void testWithoutSNIHostNameApache(String urlString) throws Exception {
            URL url = new URL(urlString); // Handshake fails
            //  URL url = new URL("https://aws.amazon.com"); // Succeeds here
            final SSLFactory sslFactory = sslFactory(true);
    
            System.out.println("Created  sslFactory");
    
            final CloseableHttpClient httpClient = apacheHttpClient(sslFactory);
            HttpGet httpGet = new HttpGet(url.toURI());
            httpGet.addHeader("User-Agent", USER_AGENT);
            System.out.println("Connection started " + urlString);
            CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
            System.out.println("Connected " + urlString);
        }
    
        private static CloseableHttpClient apacheHttpClient(final SSLFactory sslFactory) {
            if (nonNull(sslFactory)) {
                final LayeredConnectionSocketFactory socketFactory = Apache5SslUtils.toSocketFactory(sslFactory);
                final HttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create()
                        .setSSLSocketFactory(socketFactory)
                        .build();
                return HttpClients.custom()
                        .setConnectionManager(cm)
                        .build();
            } else {
                return HttpClients.createDefault();
            }
        }
    
        private static SSLFactory sslFactory(boolean validateCert) {
            final SSLFactory.Builder builder = SSLFactory.builder();
            if (validateCert) {
                builder.withDefaultTrustMaterial();
            } else {
                builder.withTrustingAllCertificatesWithoutValidation();
            }
            builder.withSecurityProvider(new BouncyCastleJsseProvider(true, new BouncyCastleFipsProvider()))
                    .withProtocols("TLSv1.2", "TLSv1.3")
                    .build();
            System.out.println("Building sslFactory");
            return builder.build();
        }
    }
    

    The above is the simulation code for reproducing the issue

    This is tested with openjdk 11

    java --version
    openjdk 11.0.17 2022-10-18
    OpenJDK Runtime Environment Temurin-11.0.17+8 (build 11.0.17+8)
    

    The test passes in all OS except in Windows server (2012-2022) and WSL based linux and fails intermittently with the below exception and it very slow and passes sometimes ruling out SSL protocol issues

    Jan 05, 2023 9:33:08 PM org.bouncycastle.jsse.provider.ProvTlsClient notifyAlertRaised
    WARNING: Client raised fatal(2) internal_error(80) alert: Failed to write record
    java.net.SocketException: Software caused connection abort: socket write error
            at java.base/java.net.SocketOutputStream.socketWrite0(Native Method)
            at java.base/java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:110)
            at java.base/java.net.SocketOutputStream.write(SocketOutputStream.java:150)
            at org.bouncycastle.tls.RecordStream.writeRecord(RecordStream.java:307)
            at org.bouncycastle.tls.TlsProtocol.safeWriteRecord(TlsProtocol.java:946)
            at org.bouncycastle.tls.TlsProtocol.sendChangeCipherSpecMessage(TlsProtocol.java:1811)
            at org.bouncycastle.tls.TlsProtocol.sendChangeCipherSpec(TlsProtocol.java:1803)
            at org.bouncycastle.tls.TlsClientProtocol.handleHandshakeMessage(TlsClientProtocol.java:658)
            at org.bouncycastle.tls.TlsProtocol.processHandshakeQueue(TlsProtocol.java:711)
            at org.bouncycastle.tls.TlsProtocol.processRecord(TlsProtocol.java:587)
            at org.bouncycastle.tls.RecordStream.readRecord(RecordStream.java:245)
            at org.bouncycastle.tls.TlsProtocol.safeReadRecord(TlsProtocol.java:875)
            at org.bouncycastle.tls.TlsProtocol.blockForHandshake(TlsProtocol.java:422)
    
    

    Not able proceed further debugging with Wireshark the TLS is not sending the client hello

    This issues only happens with Windows server and WSL and passes in all other os including windows 11 home

    opened by srinirag2016 0
  • PoC for separate session keys for password based encryption

    PoC for separate session keys for password based encryption

    While implementing my pgcrypto-kt library (a Kotlin reimplementation of the pgcrypto postgres extension for client side encryption) I faced 2 problems:

    1. implementing the sess-key option was not directly¹ possible, since PBE encryption method does not trigger session info generation
    2. implementing the s2k-cipher-algo option was not directly¹ possible, since the PBE encryption method will always use the cipher algo used for data.

    ¹: I eventually found dirty workarounds to trick BC into allowing it anyway, as posted on mailing list.

    This PR extends the PGPKeyEncryptionMethodGenerator interface by the wantsSessionInfo(): boolean method, which is default-implemented to return true. The base class PBEKeyEncryptionMethodGenerator overrides that method and makes it configurable, while defaulting to false. Unless I'm missing something here, I'd argue this should be compatible even with user customizations of the method generators. This covers problem 1.

    For problem 2 I added getSessionInfoAlgo(): Integer to PGPKeyEncryptionMethodGenerator, also default-implemented to return null. PBEKeyEncryptionMethodGenerator and PublicKeyKeyEncryptionMethodGenerator make it configurable. If the method returns a non-null value, it will be used to encrypt the session key. That covers problem 2.

    Method names are definitely open for discussion and I left out docs for the moment, until the actual code changes are accepted.

    opened by pschichtel 0
  • Failed to decrypt and verify with BouncyCastel using openssl signature and encryption

    Failed to decrypt and verify with BouncyCastel using openssl signature and encryption

    1. Openssl 3.0

    openssl smime -md sha1 -sign -inkey test_smime2.pem -signer test_smime2.cer -outform SMIME -in test.txt -out test.txt.sign

    signature body part

    MIME-Version: 1.0
    Content-Type: multipart/signed; protocol="application/x-pkcs7-signature"; micalg="sha-256"; boundary="----BC340B1A870F41887515A0BD973CD216"
    
    This is an S/MIME signed message
    
    ------BC340B1A870F41887515A0BD973CD216
    3232131313123
    ------BC340B1A870F41887515A0BD973CD216
    Content-Type: application/x-pkcs7-signature; name="smime.p7s"
    Content-Transfer-Encoding: base64
    Content-Disposition: attachment; filename="smime.p7s"
    
    MIIFdAYJKoZIhvcNAQcCoIIFZTCCBWECAQExDzANBglghkgBZQMEAgEFADALBgkq
    hkiG9w0BBwGgggMDMIIC/zCCAeegAwIBAgIJANQa1yivHU3cMA0GCSqGSIb3DQEB
    CwUAMBYxFDASBgNVBAMMCyoqKi53ZWJzaXRlMB4XDTIyMTEyMzAyNDEwNFoXDTMy
    MTEyMDAyNDEwNFowFjEUMBIGA1UEAwwLKioqLndlYnNpdGUwggEiMA0GCSqGSIb3
    DQEBAQUAA4IBDwAwggEKAoIBAQDxbGduOPXFokDzvGYg1nx3HFqTNTtNL29i7ZV5
    iB5sxrtTk9nqg3RwaTqkxqOhiybN0c5D8PJgow/bn4E5rfTJTCVmrKXnW0Pdzu2y
    fWdr3x29j7FLSFs0bkyLJPvHoEO3BdvX+tyUVJ28wjrduHfMOXwyuSsF9un3CpCc
    ENwRsj6Rf2oKXOkWQZob/b+syR4WiaHlevsXbx7J74/9ygwwddCFh51upPG3aaZV
    rp9zehGFDVfBHtbq6dJdArFj5GnTRN4IRBhwYa80hEN5+qRRl9AWCkjNW+Dzy6Q0
    QYHq7Nr3fMZSgokDoz4kP3FQ8K+2zK1qGAmvPMaJLbXXEDFfAgMBAAGjUDBOMB0G
    A1UdDgQWBBRHHSrgb3544RiGh35DIjkkBWldLTAfBgNVHSMEGDAWgBRHHSrgb354
    4RiGh35DIjkkBWldLTAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQB5
    9sEcO4Bg1pKzb9qcwcTPtQvYdz9n9ZqgVNjb54oquqMI2tZCp2r7tQ/DP4kOUkn3
    RuQb+tflILHDZuvvmytfH6nCZpLK0h4wrhMwZBzrRFSUGxOOAWk+nNv//+WAKT1u
    DFugHnlMcdDSwVHVbhTN/ozpprAiSoqRNk4MNrXh85rNYVNWQUKEqaiLAOXlkjYP
    q9kEai1alAS6k74KLvTZ+l9ec2tHEFBwmHB7zZhqgdUTFIYsINkHTNLIdrA0C71H
    mB1bM3XhVB9m5lLEmY5/rILbwKz1xOQYdVs7QpAPenRlcGYWdIHM0sLKbFmnZXQL
    qEGm4fACvAMgGxE5CqBmMYICNTCCAjECAQEwIzAWMRQwEgYDVQQDDAsqKioud2Vi
    c2l0ZQIJANQa1yivHU3cMA0GCWCGSAFlAwQCAQUAoIHkMBgGCSqGSIb3DQEJAzEL
    BgkqhkiG9w0BBwEwHAYJKoZIhvcNAQkFMQ8XDTIyMTIyODExMDAyOFowLwYJKoZI
    hvcNAQkEMSIEINTHdDYM+9de9p+GawLs5LXnSZg9Ab+R5FAGYIkiIjIKMHkGCSqG
    SIb3DQEJDzFsMGowCwYJYIZIAWUDBAEqMAsGCWCGSAFlAwQBFjALBglghkgBZQME
    AQIwCgYIKoZIhvcNAwcwDgYIKoZIhvcNAwICAgCAMA0GCCqGSIb3DQMCAgFAMAcG
    BSsOAwIHMA0GCCqGSIb3DQMCAgEoMA0GCSqGSIb3DQEBAQUABIIBAOcyN59yPm5I
    eSEisyWSrV6gE6R871+3pIVVboJQtKCeG1f0OzWrZ8N+T56gAdgEuzQqkaTcd+/8
    3yd16VJ3Q3EMho1Ykx1zXETYLs+ytWAYu0n7kINDNkqKgrE5OKa/ZsJ7Ni9v5TPk
    KpxJrLu6vy1LEsoX6LAczw/tZpbD60f8sUNXIkWhHvHQFjT+yaxaf89w2H2rVpq9
    wd9dR6WlkrpjF41uReN8EHnwxlg4v1fOmax6tHWztl1U/Nnfo6+QuKZKMGQdY1lD
    dXoac7aLLMZAMvm82N8Z9KUdYBguWV87b/+MDc7TjP6klca6BEWzsQPf94jo+qxc
    2CeTeOJD5bU=
    
    ------BC340B1A870F41887515A0BD973CD216--
    
    2. BC  decrypt code
    
    ```
    SMIMEEnveloped m = new SMIMEEnveloped(bodyPart);
                RecipientId  recId = new JceKeyTransRecipientId(cert);
    //            RecipientId  recId = new JceKeyTransRecipientId(cert);
                RecipientInformationStore  recipientsInfo = m.getRecipientInfos();
                RecipientInformation recipientInfo = recipientsInfo.get(recId);
                if (recipientInfo == null) {
                    throw new SMIMEException("Invalid encrypted content");
                }
                JceKeyTransEnvelopedRecipient recipient = new JceKeyTransEnvelopedRecipient(privateKey);
                recipient.setProvider(EcmtConstant.BC_PROVIDER);
                ByteArrayInputStream ins = new ByteArrayInputStream(recipientInfo.getContent(recipient));
    ```
    
    3.BC  verify code
    
    ```
          bodyPart = new MimeBodyPart(new ByteArrayInputStream(getDecryptedMessage().getBytes()));
    //            MimeMultipart mimeMultipart = new MimeMultipart();
                SMIMESigned signed = new SMIMESigned((MimeMultipart)bodyPart.getContent());
                SignerInformationStore signers = signed.getSignerInfos();
                Iterator signerInfos = signers.getSigners().iterator();
    
                while (signerInfos.hasNext()) {
                    SignerInformation signerInfo = (SignerInformation)signerInfos.next();
                    // if (!signerInfo.verify(cert, "BC")) {  // Deprecated
                    // TODO: revise the choice of components
                    SignerInformationVerifier verifier =
                            new BcRSASignerInfoVerifierBuilder(new DefaultCMSSignatureAlgorithmNameGenerator(),
                                    new DefaultSignatureAlgorithmIdentifierFinder(),
                                    new DefaultDigestAlgorithmIdentifierFinder(),
                                    new BcDigestCalculatorProvider())
                                    .build(new JcaX509CertificateHolder(cert));
                    if (!signerInfo.verify(verifier)) {
                        throw new SMIMEException("Verification failed");
                    }
    
    ```
    
    
    
    opened by lihongbing0801 0
  • false

    false "No CRLs found for issuer "cn=QuoVadis Root CA 2 G3,o=QuoVadis Limited,c=BM""

    For the attached certificate, there is a CRL in http://crl.quovadisglobal.com/qvrca2g3.crl

    why does the validator fail with ?

    Caused by: org.bouncycastle.jce.provider.RecoverableCertPathValidatorException: No CRLs found for issuer "cn=QuoVadis Root CA 2 G3,o=QuoVadis Limited,c=BM" at org.bouncycastle.jce.provider.CertPathValidatorUtilities.checkCRLsNotEmpty(CertPathValidatorUtilities.java:1413) at org.bouncycastle.jce.provider.CertPathValidatorUtilities.getCompleteCRLs(CertPathValidatorUtilities.java:1204) at org.bouncycastle.jce.provider.RFC3280CertPathUtilities.checkCRL(RFC3280CertPathUtilities.java:1692) at org.bouncycastle.jce.provider.RFC3280CertPathUtilities.checkCRLs(RFC3280CertPathUtilities.java:1907) at org.bouncycastle.jce.provider.ProvCrlRevocationChecker.check(ProvCrlRevocationChecker.java:53) at org.bouncycastle.jce.provider.ProvRevocationChecker.check(ProvRevocationChecker.java:165) at java.base/java.security.cert.PKIXCertPathChecker.check(PKIXCertPathChecker.java:176) at org.bouncycastle.jce.provider.RFC3280CertPathUtilities.processCertA(RFC3280CertPathUtilities.java:1445) at org.bouncycastle.jce.provider.PKIXCertPathValidatorSpi_8.engineValidate(PKIXCertPathValidatorSpi_8.java:353) at org.bouncycastle.jce.provider.PKIXCertPathBuilderSpi_8.build(PKIXCertPathBuilderSpi_8.java:210) at org.bouncycastle.jce.provider.PKIXCertPathBuilderSpi_8.build(PKIXCertPathBuilderSpi_8.java:266) at org.bouncycastle.jce.provider.PKIXCertPathBuilderSpi_8.engineBuild(PKIXCertPathBuilderSpi_8.java:119) at java.base/java.security.cert.CertPathBuilder.build(CertPathBuilder.java:297)

    see also https://github.com/bcgit/bc-java/issues/800

    opened by ralfhauser 3
  • TrustAllX509TrustManager - lint error

    TrustAllX509TrustManager - lint error

    Hi, I write concerning below lint errors we got for our android project.

    Ofc adding to baseline would resolve the issue but that's not really the best approach I guess (implementation could change in the future etc.). Any suggestions or awareness for this already?

    Thx in advance.

    <issue
        id="TrustAllX509TrustManager"
        message="`checkClientTrusted` is empty, which could cause insecure network traffic due to trusting arbitrary TLS/SSL certificates presented by peers">
        <location
            file="org/bouncycastle/jsse/BCX509ExtendedTrustManager.class"/>
    </issue>
    
    <issue
        id="TrustAllX509TrustManager"
        message="`checkClientTrusted` is empty, which could cause insecure network traffic due to trusting arbitrary TLS/SSL certificates presented by peers">
        <location
            file="org/bouncycastle/jsse/BCX509ExtendedTrustManager.class"/>
    </issue>
    
    <issue
        id="TrustAllX509TrustManager"
        message="`checkServerTrusted` is empty, which could cause insecure network traffic due to trusting arbitrary TLS/SSL certificates presented by peers">
        <location
            file="org/bouncycastle/jsse/BCX509ExtendedTrustManager.class"/>
    </issue>
    
    <issue
        id="TrustAllX509TrustManager"
        message="`checkServerTrusted` is empty, which could cause insecure network traffic due to trusting arbitrary TLS/SSL certificates presented by peers">
        <location
            file="org/bouncycastle/jsse/BCX509ExtendedTrustManager.class"/>
    </issue>
    
    <issue
        id="TrustAllX509TrustManager"
        message="`checkClientTrusted` is empty, which could cause insecure network traffic due to trusting arbitrary TLS/SSL certificates presented by peers">
        <location
            file="org/bouncycastle/est/jcajce/JcaJceUtils$1.class"/>
    </issue>
    
    <issue
        id="TrustAllX509TrustManager"
        message="`checkServerTrusted` is empty, which could cause insecure network traffic due to trusting arbitrary TLS/SSL certificates presented by peers">
        <location
            file="org/bouncycastle/est/jcajce/JcaJceUtils$1.class"/>
    </issue>
    
    <issue
        id="TrustAllX509TrustManager"
        message="`checkClientTrusted` is empty, which could cause insecure network traffic due to trusting arbitrary TLS/SSL certificates presented by peers">
        <location
            file="org/bouncycastle/est/jcajce/JcaJceUtils$2.class"/>
    </issue>
    
    opened by daniel-tailored 0
  • Tagged releases

    Tagged releases

    Hey! It would be helpful for packagers (e.g. the Debian Team) to package BouncyCastle, if releases were tagged.

    Debian unstable for example only has 1.72 packaged, but 1.72.3 is already available, yet untagged. Tagged releases would probably help them pick up the patch releases quicker.

    opened by vanitasvitae 3
Owner
Legion of the Bouncy Castle Inc
Legion of the Bouncy Castle Inc
Java Project based on Java and Encryption using Cryptography algorithms

Symmetric-Encryption-Cryptography-in-Java Java Project based on Java and Encryption using Cryptography algorithms Project Aim Develop Java program to

Muhammad Asad 6 Feb 3, 2022
A mitigation for CVE-2021-44228 (log4shell) that works by patching the vulnerability at runtime. (Works with any vulnerable java software, tested with java 6 and newer)

Log4jPatcher A Java Agent based mitigation for Log4j2 JNDI exploits. This agent employs 2 patches: Disabling all Lookup conversions (on supported Log4

null 45 Dec 16, 2022
Java binding to the Networking and Cryptography (NaCl) library with the awesomeness of libsodium

kalium - Java binding to the Networking and Cryptography (NaCl) library A Java binding to Networking and Cryptography library by Daniel J. Bernstein.

Bruno Oliveira da Silva 206 Oct 5, 2022
A small and easy-to-use one-time password generator library for Java according to RFC 4226 (HOTP) and RFC 6238 (TOTP).

OTP-Java A small and easy-to-use one-time password generator for Java according to RFC 4226 (HOTP) and RFC 6238 (TOTP). Table of Contents Features Ins

Bastiaan Jansen 106 Dec 30, 2022
Security engine for Java (authentication, authorization, multi frameworks): OAuth, CAS, SAML, OpenID Connect, LDAP, JWT...

pac4j is an easy and powerful security engine for Java to authenticate users, get their profiles and manage authorizations in order to secure web appl

PAC4J 2.2k Dec 30, 2022
An authorization library that supports access control models like ACL, RBAC, ABAC in Java

jCasbin News: still worry about how to write the correct jCasbin policy? Casbin online editor is coming to help! Try it at: http://casbin.org/editor/

Casbin 2k Dec 30, 2022
PicketLink is a security framework for securing Java EE applications.

PicketLink http://picketlink.org Java EE Application Security Identity Management Federation Social REST Security Standard-based Security This reposit

PicketLink 92 Feb 21, 2022
OACC (Object ACcess Control) is an advanced Java Application Security Framework

OACC Java Application Security Framework What is OACC? OACC - pronounced [oak] - is a fully featured API to both enforce and manage your application's

null 103 Nov 24, 2022
okta-auth-java

Okta Java Authentication SDK Release status Need help? Getting started Usage guide Configuration reference Building the SDK Contributing The Okta Auth

Okta, Inc 34 Sep 30, 2022
JSON Web Token (JWT) implementation for Java with support for signatures (JWS), encryption (JWE) and web keys (JWK).

Nimbus JOSE+JWT Nimbus JOSE+JWT is a popular open source (Apache 2.0) Java library which implements the Javascript Object Signing and Encryption (JOSE

Connect2ID 35 Jul 1, 2022
破解 Java 混淆工具 Allatori

AllatoriCrack 基于当前最新的 7.6 版本 简介: 破解 Java 混淆工具 Allatori 官网 并进行了部分加密功能的小修改 allatori 本身使用方法特别简单 命令行输入 java -Xms128m -Xmx512m -jar allatori.jar config.xml

null 161 Jan 4, 2023
Amazon Selling Partner JAVA SDK SP API

amazon-sp-api amazon sp api java sdk 背景: 亚马逊(amazon)在2020年10月推出了新的替代mws的api方案,称为Selling Partner API(SP-API)。sp-api在修改原mws的接口方式的基础上引入了aws的IAM权限管理,增加了开发

penghp 93 Nov 20, 2022
Java bytecode obfuscator with GUI

Bozar A Java bytecode obfuscator with GUI Usage Download the version you want in releases for your platform Run the executable. Done. Let me know if o

null 101 Dec 31, 2022
A java implementation of Enigma, and a modern attack to decrypt it.

Java Enigma This is a Java implementation of an Enigma machine, along with code that attempts to break the encryption. This code is associated with an

Michael Pound 584 Jan 4, 2023
Engin Demiroğun düzenlemiş olduğu (Java & React) Yazılım Geliştirici Yetiştirme Kampında yapmış olduğum ödevleri içermektedir.

Java-React-Yazilim-Gelistirici-Yetistirme-Kampi-Odevler Engin Demiroğun düzenlemiş olduğu (Java & React) Yazılım Geliştirici Yetiştirme Kampında yapmı

Baran Emre Türkmen 2 Apr 26, 2022
Kodlamaio Yazılım Geliştirici Yetiştirme Kampı (JAVA + REACT) ödev listesidir.

JavaHomeworks Kodlamaio Yazılım Geliştirici Yetiştirme Kampı (JAVA + REACT) ödev listesidir. JavaRecapDemo1 kodlama.io ileri java kampı 2. gün ödevidi

Rahim Cubuk 3 May 10, 2021
Java solutions for LeetCode

leetcode-java Java solutions for LeetCode Environment Intellij IDEA 2021.2 JDK 16.0.1 Gradle 7.1 Junit 5.7 ProblemList # Title Difficulty Link Solutio

null 5 Aug 5, 2021
Simple Hospital Managers Project GUI Java

Hospital-Managers-GUI-Java Simple Hospital Managers Project GUI Java To Run Code You just need to run MainClass.java in any IDE I make a YouTube Video

Ali Abdollahian Noghabi 2 Feb 4, 2022
'Effective Java 3/E' 스터디 저장소입니다.

Effective Java 스터디 Effective Java 3/E 스터디 저장소입니다. 0. 스터디 정보 기간 : 2021/08/19 ~ 참여 인원 : 강동민(@riyenas0925), 김하늬(@kimhanui) 도서 : 이펙티브 자바 Effective Java 3/

null 3 Feb 26, 2022