### Content Example: 'This is some sample content.' Source: https://github.com/bcgit/bc-lts-java/blob/main/core/src/test/data/rfc4134/rfc4134.txt Defines the sample content string 'ExContent' used in the S/MIME message examples. It also provides the hexadecimal representation and MD5/SHA-1 hashes of this content. ```text This is some sample content. ``` -------------------------------- ### Private Key Example: AlicePrivRSASign Source: https://github.com/bcgit/bc-lts-java/blob/main/core/src/test/data/rfc4134/rfc4134.txt Defines the private RSA signing key for 'Alice' in ASN.1 format. This key is used in the S/MIME message examples. ```asn1 0 30 630: SEQUENCE { 4 02 1: INTEGER 0 7 30 13: SEQUENCE { 9 06 9: OBJECT IDENTIFIER : 20 05 0: NULL : } 22 04 608: OCTET STRING, encapsulates { 26 30 604: SEQUENCE { 30 02 1: INTEGER 0 33 02 129: INTEGER : : } : } ``` -------------------------------- ### Private Key Example: AlicePrivDSSSign Source: https://github.com/bcgit/bc-lts-java/blob/main/core/src/test/data/rfc4134/rfc4134.txt Defines the private DSS signing key for 'Alice' in ASN.1 format. This key is used in the S/MIME message examples. ```asn1 0 30 331: SEQUENCE { 4 02 1: INTEGER 0 7 30 299: SEQUENCE { 11 06 7: OBJECT IDENTIFIER dsa (1 2 840 10040 4 1) : 20 30 286: SEQUENCE { 24 02 129: INTEGER : 156 02 21: INTEGER : 179 02 128: INTEGER : : } : } 310 04 23: OCTET STRING, encapsulates { 312 02 21: INTEGER : : } : } ``` -------------------------------- ### Hashing Example: MD5 and SHA-1 hashes of sample content Source: https://github.com/bcgit/bc-lts-java/blob/main/core/src/test/data/rfc4134/rfc4134.txt Provides the MD5 and SHA-1 hash values for the sample content 'ExContent'. These hashes are used to verify the integrity of the content. ```text 9898 cac8 fab7 691f f89d c207 24e7 4a04 ``` ```text 406a ec08 5279 ba6e 1602 2d9e 0629 c022 9687 dd48 ``` -------------------------------- ### Check Java Version Source: https://github.com/bcgit/bc-lts-java/blob/main/benchmark/README.md Displays the currently installed Java version. This is a prerequisite for running benchmarks, as the build requires Java 21+ to produce JDK 21 code. ```shell java -version ``` -------------------------------- ### Example Base64 Encoded Content Source: https://github.com/bcgit/bc-lts-java/blob/main/core/src/test/data/rfc4134/rfc4134.txt This snippet shows an example of Base64 encoded content, typically used for transmitting binary data in text-based formats. The data is presented as a string of characters from the Base64 alphabet. ```Base64 VGhpcyBpcyBzb21lIHNhbXBsZSBjb250ZW50Lg== ``` -------------------------------- ### Enroll Certificate using EST Client Source: https://github.com/bcgit/bc-lts-java/blob/main/test/est/example/README.md Performs certificate enrollment with an EST server. Requires a trust anchor for server verification and can optionally use a keystore for client authentication. This example generates a CSR internally and specifies the common name. ```bash ./enroll.sh -t server.ta.pem -u testrfc7030.com:8443 --auth estuser:estpwd -c BARRY Subject: CN=BARRY Issuer: CN=estExampleCA Serial Number: 8727 Not Before: Tue Feb 07 16:00:25 AEDT 2017 Not After: Wed Feb 07 16:00:25 AEDT 2018 Signature Algorithm: org.bouncycastle.asn1.x509.AlgorithmIdentifier@ca7a8819 ``` -------------------------------- ### Example Alice Private RSA Key Source: https://github.com/bcgit/bc-lts-java/blob/main/core/src/test/data/rfc4134/rfc4134.txt This snippet shows a private key for Alice using the RSA algorithm. It's encoded in a standard format, likely PEM, for use in cryptographic applications. ```PEM MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAOCJczmN2PX16Id2OX9OsA W7U4PeD7er3H3HdSkNBS5tEt+mhibU0m+qWCn8l+z6glEPMIC+sVCeRkTxLLvYMs/GaG8H 2bBgrL7uNAlqE/X3BQWT3166NVbZYf8Zf8mB5vhs6odAcO+sbSx0ny36VTq5mXcCpkhSjE 7zVzhXdFdfAgMBAAECgYAApAPDJ0d2NDRspoa1eUkBSy6K0shissfXSAlqi5H3NvJ11ujN FZBgJzFHNWRNlc1nY860n1asLzduHO4Ovygt9DmQbzTYbghb1WVq2EHzE9ctOV7+M8v/Ke ``` -------------------------------- ### S/MIME Authenticated Attributes Example Source: https://github.com/bcgit/bc-lts-java/blob/main/core/src/test/data/rfc4134/rfc4134.txt This snippet shows an example of S/MIME authenticated attributes, specifically the 'equivalentLabels' attribute. It includes the OBJECT IDENTIFIER for this attribute and a SET containing a SEQUENCE with an INTEGER value. ```ASN.1 SEQUENCE { OBJECT IDENTIFIER id-aa-equivalentLabels (1 2 840 113549 1 9 16 2 9) (S/MIME Authenticated Attributes (1 2 840 113549 1 9 16 2)) SET { SEQUENCE { SET { INTEGER 1 } } } } ``` -------------------------------- ### Create CodeQL C++ Database Source: https://github.com/bcgit/bc-lts-java/blob/main/native_c/notes.txt This command creates a CodeQL database for C++ source code. It requires the CodeQL CLI to be installed and configured. The command takes the database name, source root, programming language, and a build command as arguments. The `--overwrite` flag ensures that any existing database with the same name is replaced. ```bash codeql database create fipsnative --source-root . --language=cpp --overwrite --command "./build_linux.sh" ``` -------------------------------- ### Build and Install ARM Probe Library Source: https://github.com/bcgit/bc-lts-java/blob/main/native_c/CMakeLists.txt Creates a shared library named '${LIB_PROBE}-le' for probe functionality on ARM. It includes specified JNI headers, sets compile options for CXX, and defines a build timestamp. The library is installed to a platform-specific directory. ```cmake add_library(${LIB_PROBE}-le SHARED ${PROBE}) target_include_directories(${LIB_PROBE}-le PUBLIC ${JNI_INCLUDES}) target_compile_options(${LIB_PROBE}-le PRIVATE $<$:${PROBE_OPTIONS}>) target_compile_definitions(${LIB_PROBE}-le PUBLIC BUILD_TS="${BUILD_TS}") install(TARGETS "${LIB_PROBE}-le" LIBRARY DESTINATION ${PLATFORM_TARGET}/probe) ``` -------------------------------- ### Processing Bytes with GCMModeCipher (Java) Source: https://github.com/bcgit/bc-lts-java/blob/main/README.md Shows an example of using `GCMModeCipher` for cryptographic processing, specifically focusing on handling the output length and the return value of `processBytes`. It highlights the need to account for the bytes returned by `processBytes` when calling `doFinal` to ensure all processed data is correctly handled. ```java GCMModeCipher gcm = ...; gcm.init( ... ); byte[] out = new byte[gcm.getOutputSize(...)]; int j = gcm.processBytes(message, 0, message.length, out, 0); gcm.doFinal(out, j); ``` -------------------------------- ### Configure Big Endian Native Library (CMake - Commented Out) Source: https://github.com/bcgit/bc-lts-java/blob/main/native_c/CMakeLists.txt This commented-out section shows how to configure a 'neon-be' (big-endian) native library. It includes settings for shared library creation, include directories, compile options with the '-mbig-endian' flag for CXX, and definitions. The installation path is also specified. ```cmake # add_library(${LIB_PROBE}-be SHARED ${PROBE}) # target_include_directories(${LIB_PROBE}-be PUBLIC ${JNI_INCLUDES}) # target_compile_options(${LIB_PROBE}-be PRIVATE $<$:${PROBE_OPTIONS} -mbig-endian>) # target_compile_definitions(${LIB_PROBE}-be PUBLIC BUILD_TS=\"${BUILD_TS}\") # install(TARGETS "${LIB_PROBE}-be" LIBRARY DESTINATION ${PLATFORM_TARGET}/probe) # add_library(${LIB_NATIVE}-neon-be SHARED # ${JNI_UTIL} # ${COMMON} # ${COMMON_NEON} # ${ARM_ECB} # ${ARM_GCM} # ${ARM_CBC} # ${ARM_CFB} # ${ARM_CTR} # ${ARM_CCM} # ${ARM_SHA256} # ) # target_include_directories("${LIB_NATIVE}-neon-be" PUBLIC ${JNI_INCLUDES}) # target_compile_options("${LIB_NATIVE}-neon-be" PRIVATE $<$:${ARM64_NEON_OPTIONS} ${ARM_BE}> $<$: ${ASM_OPTIONS} ${ASM_FLAGS}>) # install(TARGETS "${LIB_NATIVE}-neon-be" LIBRARY DESTINATION ${PLATFORM_TARGET}/neon-be) ``` -------------------------------- ### Example Alice Private DSS Key Source: https://github.com/bcgit/bc-lts-java/blob/main/core/src/test/data/rfc4134/rfc4134.txt This snippet represents a private key for Alice using the Digital Signature Standard (DSS). It's encoded in a format suitable for cryptographic operations, likely PEM encoded. ```PEM MIIBSwIBADCCASsGByqGSM44BAEwggEeAoGBAIGNze2D6gqeOT7CSCij5EeT3Q7XqA7sU8 WrhAhP/5Thc0h+DNbzREjR/p+vpKGJL+HZMMg23j+bv7dM3F9piuR10DcMkQiVm96nXvn8 9J8v3UOoi1TxP7AHCEdNXYjDw7Wz41UIddU5dhDEeL3/nbCElzfy5FEbteQJllzzflvbAh UA4kemGkVmuBPG2o+4NyErYov3k80CgYAmONAUiTKqOfs+bdlLWWpMdiM5BAI1XPLLGjDD HlBd3ZtZ4s2qBT1YwHuiNrhuB699ikIlp/R1z0oIXks+kPht6pzJIYo7dhTpzi5dowfNI4 W4LzABfG1JiRGJNkS9+MiVSlNWteL5c+waYTYfEX/Cve3RUP+YdMLRgUpgObo2OQQXAhUA u0RG0aXJRgcu0P561pIH8JqFiT8= ``` -------------------------------- ### X.500 Distinguished Names (DNs) Examples Source: https://github.com/bcgit/bc-lts-java/blob/main/core/src/test/data/rfc4134/rfc4134.txt This snippet demonstrates the structure of X.500 Distinguished Names (DNs) as used in S/MIME certificates. It shows common attributes like organizationalUnitName, commonName, countryName, and organizationName, represented using ASN.1 syntax. ```ASN.1 SET { SEQUENCE { OBJECT IDENTIFIER organizationalUnitName (2 5 4 11) (X.520 id-at (2 5 4)) PrintableString 'VDA' } } SET { SEQUENCE { OBJECT IDENTIFIER commonName (2 5 4 3) (X.520 id-at (2 5 4)) PrintableString 'Bugs Bunny DSA' } } SET { SEQUENCE { OBJECT IDENTIFIER countryName (2 5 4 6) (X.520 id-at (2 5 4)) PrintableString 'US' } } SET { SEQUENCE { OBJECT IDENTIFIER organizationName (2 5 4 10) (X.520 id-at (2 5 4)) PrintableString 'US Government' } } SET { SEQUENCE { OBJECT IDENTIFIER organizationalUnitName (2 5 4 11) (X.520 id-at (2 5 4)) PrintableString 'VDA Site' } } SET { SEQUENCE { OBJECT IDENTIFIER organizationalUnitName (2 5 4 11) (X.520 id-at (2 5 4)) PrintableString 'VDA' } } SET { SEQUENCE { OBJECT IDENTIFIER commonName (2 5 4 3) (X.520 id-at (2 5 4)) PrintableString 'Elmer Fudd DSA' } } ``` -------------------------------- ### Configure neon-le Native Library (CMake) Source: https://github.com/bcgit/bc-lts-java/blob/main/native_c/CMakeLists.txt Sets compile options and definitions for the 'neon-le' native library. It targets C and ASM languages, enabling specific ARM64 NEON options and defining build-related macros. The library is then installed to a platform-specific destination. ```cmake target_compile_options("${LIB_NATIVE}-neon-le" PRIVATE $<$:${ARM64_NEON_OPTIONS}> $<$: ${ASM_OPTIONS} ${ASM_FLAGS}>) install(TARGETS "${LIB_NATIVE}-neon-le" LIBRARY DESTINATION ${PLATFORM_TARGET}/neon-le) target_compile_definitions("${LIB_NATIVE}-neon-le" PUBLIC BC_NEON BC_VARIANT=\"neon-le\" BUILD_TS=\"${BUILD_TS}\") ``` -------------------------------- ### X.509 Certificate Generation with Bouncy Castle PKIX Source: https://context7.com/bcgit/bc-lts-java/llms.txt Provides a Java example for creating self-signed X.509 certificates using the Bouncy Castle PKIX module. It includes generating RSA keys, defining certificate details, and signing the certificate. Requires Bouncy Castle. ```java import java.math.BigInteger; import java.security.*; import java.util.Date; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.cert.X509v3CertificateBuilder; import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; import org.bouncycastle.operator.ContentSigner; import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; import org.bouncycastle.jce.provider.BouncyCastleProvider; Security.addProvider(new BouncyCastleProvider()); // Generate RSA key pair KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", "BC"); keyGen.initialize(2048); KeyPair keyPair = keyGen.generateKeyPair(); // Certificate details X500Name issuer = new X500Name("CN=Test CA, O=Bouncy Castle, C=AU"); X500Name subject = new X500Name("CN=Test Certificate, O=Bouncy Castle, C=AU"); BigInteger serial = BigInteger.valueOf(System.currentTimeMillis()); Date notBefore = new Date(); Date notAfter = new Date(System.currentTimeMillis() + 365L * 24 * 60 * 60 * 1000); // Build certificate X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder( issuer, serial, notBefore, notAfter, subject, keyPair.getPublic()); // Sign certificate ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSA") .setProvider("BC").build(keyPair.getPrivate()); java.security.cert.X509Certificate cert = new JcaX509CertificateConverter() .setProvider("BC").getCertificate(certBuilder.build(signer)); System.out.println("Subject: " + cert.getSubjectX500Principal()); System.out.println("Issuer: " + cert.getIssuerX500Principal()); System.out.println("Valid until: " + cert.getNotAfter()); ``` -------------------------------- ### Initialize and Draw Google Charts Line Chart Source: https://github.com/bcgit/bc-lts-java/blob/main/benchmark/src/main/resources/report.html This JavaScript code initializes the Google Charts library, sets up a callback for when the charts are loaded, and then proceeds to draw an interactive line chart. It dynamically generates buttons to control which data series are displayed on the chart. ```javascript google.charts.load('current', {'packages': ['corechart', 'line']}); google.charts.setOnLoadCallback(loaded); function loaded() { var switches = document.getElementById("switches"); cols.forEach(item => { var button = document.createElement("button"); button.textContent = item.label + (item.selected ? " ✓" : ""); button.type = "button"; button.onclick = function (e) { if (item.selected) { item.selected = false; button.textContent = item.label; } else { item.selected = true; button.textContent = item.label + " ✓"; } drawChart(); } switches.append(button); }) drawChart(); } function drawChart() { var data = new google.visualization.DataTable(); data.addColumn('number', 'Message Size'); var table = []; var selected = []; selected.push(colData['X']); // Always first cols.forEach(item => { if (item.selected) { data.addColumn('number', item.label); selected.push(colData[item.label]); } }); // Work across selected creating a row array. var t = 0; var maxLen = 1000000; do { table.push(Array(selected.length)); maxLen = 1000000; for (var j = 0; j < selected.length; j++) { table[table.length - 1][j] = selected[j][t]; maxLen = Math.min(maxLen, selected[j].length); } t++; } while (t < maxLen); data.addRows(table); var options = { title: "--title--", subtitle: 'KB per second', hAxis: { title: 'Message Size Bytes', logScale: false }, vAxis: { title: 'Throughput KB/s', logScale: false }, }; var chart = new google.visualization.LineChart(document.getElementById('curve_chart')); chart.draw(data, options); } ``` -------------------------------- ### Include Directories Setup for BC-LTS-JAVA Source: https://github.com/bcgit/bc-lts-java/blob/main/native_c/CMakeLists.txt Configures the include paths for the project, including source directories, JNI headers, and platform-specific headers. This ensures that all necessary header files are accessible during compilation. ```cmake MESSAGE("JNI_INCLUDE_PLATFORM" ${JNI_INCLUDE_PLATFORM}) include_directories( ${CMAKE_CURRENT_SOURCE_DIR}/src ${JNI_INCLUDE} ${JNI_INCLUDE_PLATFORM} ${LTS_JAVA_HEADERS} ${LTS_TEST_JAVA_HEADERS}) ``` -------------------------------- ### Define Build Options and Project in CMake Source: https://github.com/bcgit/bc-lts-java/blob/main/native_c/CMakeLists.txt This snippet defines build options and project settings for the native components. It includes an option for code analysis and sets various library and installation path variables. It also defines the project name and its primary language as C. ```cmake option(ENABLE_CODE_ANALYSIS "Run code analysis" OFF) set(CORE_NATIVE "bc-lts-c") set(LIB_PROBE "bc-probe") set(LIB_NATIVE "bc-lts") string(TIMESTAMP BUILD_TS "%Y-%m-%dT%H:%M:%S") project(${CORE_NATIVE} LANGUAGES C) set(NATIVE_INSTALL_ROOT ${CMAKE_SOURCE_DIR}/target) # # Common sources between all CPUs ``` -------------------------------- ### Run CBC Benchmark on Intel Source: https://github.com/bcgit/bc-lts-java/blob/main/benchmark/README.md Executes a benchmark script for CBC on Intel architecture. It requires the bc-lts-java-jars to be in a specific directory structure and the library version to be provided as an argument. ```shell # # select the script supplying the library version of interest as the first argument # benchmark$ ./benchmark_linux_cbc.sh 2.73.7 ``` -------------------------------- ### Analyze CodeQL C++ Database Source: https://github.com/bcgit/bc-lts-java/blob/main/native_c/notes.txt This command analyzes a pre-existing CodeQL database using a specified query suite. It outputs the analysis results in CSV format to a specified file. The `--sarif-category` flag helps categorize the results, and `--format=csv` ensures the output is comma-separated. ```bash codeql database analyze fipsnative cpp-code-scanning.qls --sarif-category="cpp" --format=csv --output analysis.csv ``` -------------------------------- ### List bc-lts-java-jars Versions Source: https://github.com/bcgit/bc-lts-java/blob/main/benchmark/README.md Lists the contents of the bc-lts-java-jars directory, which is used to determine available library versions for benchmarking. ```shell # Assuming you are in the benchmark dir: ls -al ../../bc-lts-java-jars/ ``` -------------------------------- ### Reading Fully with Bouncy Castle Utility (Java) Source: https://github.com/bcgit/bc-lts-java/blob/main/README.md Suggests using the Bouncy Castle utility class `org.bouncycastle.util.io.Streams` for reliably reading data fully into byte arrays. This addresses the potential issue of partial reads from streams, similar to how `DataInputStream.readFully()` works in standard Java. ```java import org.bouncycastle.util.io.Streams; // ... within a method ... CipherInputStream cin = ...; byte[] buffer = new byte[expectedSize]; Streams.readFully(cin, buffer); ``` -------------------------------- ### Register Bouncy Castle Provider in Java Source: https://context7.com/bcgit/bc-lts-java/llms.txt Demonstrates how to register the Bouncy Castle security provider at runtime using `Security.addProvider()`. This enables JCA/JCE cryptographic services. An alternative static registration method is also mentioned. ```java import java.security.Security; import org.bouncycastle.jce.provider.BouncyCastleProvider; // Runtime registration Security.addProvider(new BouncyCastleProvider()); // Verify registration if (Security.getProvider("BC") != null) { System.out.println("Bouncy Castle provider registered successfully"); } // Alternative: Static registration in java.security file // security.provider.=org.bouncycastle.jce.provider.BouncyCastleProvider ``` -------------------------------- ### ChaCha20-Poly1305 AEAD Encryption in Java Source: https://context7.com/bcgit/bc-lts-java/llms.txt Implements modern authenticated encryption with associated data (AEAD) using the ChaCha20-Poly1305 algorithm. This requires Bouncy Castle crypto libraries. The example demonstrates initializing the cipher with a key, nonce, and associated data, then performing encryption and decryption. ```java import org.bouncycastle.crypto.modes.ChaCha20Poly1305; import org.bouncycastle.crypto.params.AEADParameters; import org.bouncycastle.crypto.params.KeyParameter; import java.security.SecureRandom; ChaCha20Poly1305 cipher = new ChaCha20Poly1305(); // 256-bit key and 96-bit nonce byte[] key = new byte[32]; byte[] nonce = new byte[12]; byte[] aad = "additional data".getBytes(); new SecureRandom().nextBytes(key); new SecureRandom().nextBytes(nonce); // Initialize with 128-bit tag AEADParameters params = new AEADParameters(new KeyParameter(key), 128, nonce, aad); cipher.init(true, params); // Encrypt byte[] plaintext = "Encrypt with ChaCha20-Poly1305".getBytes(); byte[] ciphertext = new byte[cipher.getOutputSize(plaintext.length)]; int len = cipher.processBytes(plaintext, 0, plaintext.length, ciphertext, 0); len += cipher.doFinal(ciphertext, len); // Decrypt cipher.init(false, params); byte[] decrypted = new byte[cipher.getOutputSize(len)]; int decLen = cipher.processBytes(ciphertext, 0, len, decrypted, 0); decLen += cipher.doFinal(decrypted, decLen); System.out.println("Decrypted: " + new String(decrypted, 0, decLen)); ``` -------------------------------- ### Build ARM NEON Optimized Native Library Source: https://github.com/bcgit/bc-lts-java/blob/main/native_c/CMakeLists.txt Constructs a shared library '${LIB_NATIVE}-neon-le' for ARM processors, leveraging NEON optimizations. It bundles JNI utilities, common ARM code, NEON-specific components, and various cryptographic algorithm implementations. ```cmake # # Arm projects LE # add_library(${LIB_NATIVE}-neon-le SHARED ${JNI_UTIL} ${COMMON} ${COMMON_NEON} ${ARM_ECB} ${ARM_GCM} ${ARM_CBC} ${ARM_CFB} ${ARM_CTR} ${ARM_CCM} ${ARM_SHA256} ${ARM_SHA224} ${ARM_SHA384} ${ARM_SHA512} ${ARM_SHA3} ${ARM_SHAKE} ${ARM_MUL} ) target_include_directories("${LIB_NATIVE}-neon-le" PUBLIC ${JNI_INCLUDES}) ``` -------------------------------- ### Extract S/MIME Binaries with Perl Source: https://github.com/bcgit/bc-lts-java/blob/main/core/src/test/data/rfc4134/rfc4134.txt This Perl script extracts binary data embedded within the RFC document. It identifies binary content by looking for lines starting with '|' and interprets specific characters following the '|' to determine the type of content (comment, filename, end-of-file, or Base64 data). The script requires Perl and is intended to be run with the RFC document as standard input. ```perl #!/usr/bin/perl # CMS Samples extraction program. v 1.1 ``` -------------------------------- ### Generate OpenPGP Key Pair in Java Source: https://context7.com/bcgit/bc-lts-java/llms.txt Generates an RSA PGP key pair for encryption and signing using the Bouncy Castle provider. It includes steps for initializing the key pair generator, creating PGP key objects, and protecting the secret key with a passphrase. Dependencies include Bouncy Castle's JCE provider and OpenPGP classes. ```java import java.security.*; import java.util.Date; import org.bouncycastle.bcpg.HashAlgorithmTags; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.openpgp.*; import org.bouncycastle.openpgp.operator.jcajce.*; Security.addProvider(new BouncyCastleProvider()); // Generate RSA key pair KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "BC"); kpg.initialize(2048, new SecureRandom()); KeyPair keyPair = kpg.generateKeyPair(); // Create PGP key pair PGPDigestCalculator sha1Calc = new JcaPGPDigestCalculatorProviderBuilder() .build().get(HashAlgorithmTags.SHA1); PGPKeyPair pgpKeyPair = new JcaPGPKeyPair( PGPPublicKey.RSA_GENERAL, keyPair, new Date()); // Create PGP secret key with passphrase protection char[] passphrase = "secret".toCharArray(); PGPSecretKey secretKey = new PGPSecretKey( PGPSignature.DEFAULT_CERTIFICATION, pgpKeyPair, "user@example.com", sha1Calc, null, // hashed subpackets null, // unhashed subpackets new JcaPGPContentSignerBuilder( pgpKeyPair.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA256), new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, sha1Calc) .setProvider("BC").build(passphrase)); PGPPublicKey publicKey = secretKey.getPublicKey(); System.out.println("Key ID: " + Long.toHexString(publicKey.getKeyID())); System.out.println("User ID: " + publicKey.getUserIDs().next()); ``` -------------------------------- ### Configure Native Library Build for Linux Intel Source: https://github.com/bcgit/bc-lts-java/blob/main/native_c/CMakeLists.txt Sets up build configurations for Linux on Intel x86_64 processors. It defines optimization flags, C compiler flags, and platform-specific include paths. Debug builds can be enabled by setting the LTS_DEV environment variable. ```cmake if (${CMAKE_SYSTEM_NAME} STREQUAL "Linux") if (${CMAKE_SYSTEM_PROCESSOR} STREQUAL "x86_64") MESSAGE("Building for Linux Intel") set(OPTIMISE_FLAG -O3) # Test for dev environment. # If dev environment variable LTS_DEV exists then turn off optimisations and switch on debugging # if (DEFINED ENV{LTS_DEV}) set(OPTIMISE_FLAG -g) MESSAGE("DEBUG BUILD --- NOT OPTIMISED") else () MESSAGE("RELEASE BUILD --- OPTIMISED") endif () set(JNI_INCLUDE_PLATFORM ${JNI_INCLUDE}/linux) set(PLATFORM_TARGET ${NATIVE_INSTALL_ROOT}/linux/x86_64) set(CMAKE_C_FLAGS "-std=c99") set(OPTIONS -Wconversion -Werror=return-type -static-libgcc -z noexecstack) set(PROBE_OPTIONS ${OPTIMISE_FLAG} -msse4.1 ${OPTIONS}) set(AVX_OPTIONS ${OPTIMISE_FLAG} -mavx -msha -maes -mpclmul -mrdrnd -mrdseed -mlzcnt ${OPTIONS}) set(VAES_OPTIONS ${OPTIMISE_FLAG} -mavx -msha -maes -mpclmul -mrdrnd -mrdseed -mlzcnt -mvaes -mavx2 ${OPTIONS}) set(VAESF_OPTIONS ${OPTIMISE_FLAG} -mavx -msha -maes -mpclmul -mrdrnd -mrdseed -mlzcnt -mvaes -mavx2 -mavx512f -mavx512bw -mvpclmulqdq ${OPTIONS}) set(ASM_OPTIONS -f elf64) set(COMMON_ASM intel/common_sysV.asm) endif () else () MESSAGE("Building for Windows Intel") FILE(TO_CMAKE_PATH "${JNI_INCLUDE}/win32" JNI_INCLUDE_PLATFORM) set(PLATFORM_TARGET ${NATIVE_INSTALL_ROOT}/windows/x86_64) set(CMAKE_C_FLAGS "-std=c99") set(OPTIONS /Wall) set(PROBE_OPTIONS ${OPTIONS}) set(SSE_OPTIONS ${OPTIONS}) set(AVX_OPTIONS ${OPTIONS}) set(VAES_OPTIONS /arch:AVX2 ${OPTIONS}) set(VAESF_OPTIONS /arch:AVX512 ${OPTIONS}) endif () ``` -------------------------------- ### Define Source Files for Intel Native Implementations Source: https://github.com/bcgit/bc-lts-java/blob/main/native_c/CMakeLists.txt Defines sets of source files for various native implementations used in the project. This includes probe, identification, common utilities, and different cipher modes (ECB, CBC, CFB) with varying levels of optimization (SSE, AVX, VAES, VAESF). ```cmake set(PROBE intel/jni/variant_selector_intel.c) set(IDENT_IMPL intel/jni/ident_jni.c intel/jni/native_features.c) set(COMMON intel/common.c intel/common.h intel/util/util.c intel/util/util.h intel/util/xor.h ${COMMON_ASM}) set(MUL_AVX intel/jni/cmul_jni.c intel/mul/cmul.h intel/mul/cmul128.c) set(MUL_VAESF intel/jni/cmul_jni.c intel/mul/cmul.h intel/mul/cmul128.c) set(ECB intel/jni/ecb_jni.c intel/ecb/ecb128w.c intel/ecb/ecb.h intel/ecb/ecb.c) set(ECB_VAES intel/jni/ecb_jni.c intel/ecb/ecb256w.c intel/ecb/ecb.h intel/ecb/ecb.c) set(ECB_VAESF intel/jni/ecb_jni.c intel/ecb/ecb512w.c intel/ecb/ecb.h intel/ecb/ecb.c) set(CBC intel/cbc/cbc.h intel/cbc/cbc.c intel/cbc/cbc128.c intel/jni/cbc_jni.c ) set(CBC_VAES intel/cbc/cbc.h intel/cbc/cbc.c intel/cbc/cbc256.c intel/jni/cbc_jni.c ) set(CBC_VAESF intel/cbc/cbc.h intel/cbc/cbc.c intel/cbc/cbc512.c intel/jni/cbc_jni.c ) set(CBC_PC intel/packet/cbc_pc/cbc_pc.h intel/packet/cbc_pc/cbc_pc.c intel/packet/cbc_pc/cbc_pc128.c intel/jni/cbc_pc_jni.c intel/packet/packet_utils.h intel/packet/packet_utils.c ) set(CBC_PC_VAES intel/packet/cbc_pc/cbc_pc.h intel/packet/cbc_pc/cbc_pc.c intel/packet/cbc_pc/cbc_pc256.c intel/jni/cbc_pc_jni.c intel/packet/packet_utils.h intel/packet/packet_utils.c ) set(CBC_PC_VAESF intel/packet/cbc_pc/cbc_pc.h intel/packet/cbc_pc/cbc_pc.c intel/packet/cbc_pc/cbc_pc512.c intel/jni/cbc_pc_jni.c intel/packet/packet_utils.h intel/packet/packet_utils.c ) set(CFB intel/cfb/cfb.h intel/cfb/cfb.c intel/cfb/cfb128.c intel/jni/cfb_jni.c ) set(CFB_VAES intel/cfb/cfb.h intel/cfb/cfb.c intel/cfb/cfb256.c intel/jni/cfb_jni.c ) set(CFB_VAESF intel/cfb/cfb.h intel/cfb/cfb.c intel/cfb/cfb512.c ``` -------------------------------- ### Fetch CA Certificates using EST Client Source: https://github.com/bcgit/bc-lts-java/blob/main/test/est/example/README.md Fetches CA certificates from an EST server. Requires a trust anchor to validate the server. If validation fails, the operation will error. ```bash ./cacerts.sh -u testrfc7030.com:8443 -t server.ta.pem Fetched CA Certs: -----BEGIN CERTIFICATE----- MIIBUjCB+aADAgECAgkAwc6rXEzvJGowCQYHKoZIzj0EATAXMRUwEwYDVQQDEwxl c3RFeGFtcGxlQ0EwHhcNMTYwOTA3MTcxOTM5WhcNMTcwOTA3MTcxOTM5WjAXMRUw EwYDVQQDEwxlc3RFeGFtcGxlQ0EwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAQs JmLuU8faAKwGQs6A0WpYlwdwR/C0U6kvIIMjcLdPX+OBtYtHo2B8WMDOU5AkGgZ+ Bmy9ZdaZj2BTqGqsiNSioy8wLTAMBgNVHRMEBTADAQH/MB0GA1UdDgQWBBTSse7P EyPT3DkGbsMutPbRjWpKdDAJBgcqhkjOPQQBA0kAMEYCIQDtdmXQD7TQo/mLMsce Hw+Xzwb+1WhQoG8ra1PkEugcygIhAPOZ/L5cnpw/1S8rpVfxSVXUOQpatrgIo50y WmAvxibh -----END CERTIFICATE----- ``` -------------------------------- ### Configure Native Cleanup Delay (Java System Property) Source: https://github.com/bcgit/bc-lts-java/blob/main/README.md Demonstrates how to set a cleanup delay for native allocations using the org.bouncycastle.native.cleanup_delay system property. This property can be set to a duration in milliseconds or seconds to control when native memory is freed after a class is available for garbage collection. The default value is zero, meaning immediate cleanup. ```properties -Dorg.bouncycastle.native.cleanup_delay=10ms -Dorg.bouncycastle.native.cleanup_delay=1s ``` -------------------------------- ### Handling Partial Reads from CipherInputStream (Java) Source: https://github.com/bcgit/bc-lts-java/blob/main/README.md Illustrates a common scenario when using CipherInputStream where a read operation might not return the expected amount of data. It emphasizes the importance of checking the actual number of bytes read, as per the InputStream.read(byte[], int, int) specification, to correctly handle partial or variable data returns. ```java CipherInputStream cin = ... byte[] dataIExpect = new byte[...]; int l = cin.read(dataIExpect); // Does `l` equal what I expect it to? Am I checking this? ``` -------------------------------- ### Create and Verify CMS Signed Data in Java Source: https://context7.com/bcgit/bc-lts-java/llms.txt Generates a CMS signed data structure, signs it with a private key, and then verifies the signature using the corresponding certificate. Requires Bouncy Castle libraries. ```java import java.security.*; import java.security.cert.X509Certificate; import java.util.*; import org.bouncycastle.cert.jcajce.JcaCertStore; import org.bouncycastle.cms.*; import org.bouncycastle.cms.jcajce.*; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder; import org.bouncycastle.util.Store; Security.addProvider(new BouncyCastleProvider()); // Assume keyPair and cert are pre-generated KeyPair keyPair = /* ... */; X509Certificate cert = /* ... */; // Create signed data generator CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); // Add signer ContentSigner sha256Signer = new JcaContentSignerBuilder("SHA256withRSA") .setProvider("BC").build(keyPair.getPrivate()); gen.addSignerInfoGenerator( new JcaSignerInfoGeneratorBuilder( new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()) .build(sha256Signer, cert)); // Add certificate List certList = new ArrayList<>(); certList.add(cert); Store certs = new JcaCertStore(certList); gen.addCertificates(certs); // Sign data byte[] data = "Content to sign".getBytes(); CMSTypedData content = new CMSProcessableByteArray(data); CMSSignedData signedData = gen.generate(content, true); // true = encapsulate content // Verify signature Store certStore = signedData.getCertificates(); SignerInformationStore signers = signedData.getSignerInfos(); for (SignerInformation signer : signers.getSigners()) { Collection certCollection = certStore.getMatches(signer.getSID()); X509Certificate signerCert = new JcaX509CertificateConverter() .getCertificate((org.bouncycastle.cert.X509CertificateHolder)certCollection.iterator().next()); SignerInformationVerifier verifier = new JcaSimpleSignerInfoVerifierBuilder() .setProvider("BC").build(signerCert); System.out.println("Signature valid: " + signer.verify(verifier)); } ``` -------------------------------- ### RSA Key Generation and Encryption with Bouncy Castle JCA Source: https://context7.com/bcgit/bc-lts-java/llms.txt Demonstrates generating RSA key pairs and performing encryption/decryption using the Bouncy Castle provider within the Java Cryptography Architecture (JCA). Requires Bouncy Castle and standard Java security libraries. ```java import java.security.*; import javax.crypto.Cipher; import org.bouncycastle.jce.provider.BouncyCastleProvider; Security.addProvider(new BouncyCastleProvider()); // Generate RSA key pair KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", "BC"); keyGen.initialize(2048, new SecureRandom()); KeyPair keyPair = keyGen.generateKeyPair(); // Encrypt with public key Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC"); cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic()); byte[] plaintext = "Secret message".getBytes(); byte[] ciphertext = cipher.doFinal(plaintext); // Decrypt with private key cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate()); byte[] decrypted = cipher.doFinal(ciphertext); System.out.println("Decrypted: " + new String(decrypted)); // Output: Decrypted: Secret message ``` -------------------------------- ### Encrypt File with OpenPGP Public Key in Java Source: https://context7.com/bcgit/bc-lts-java/llms.txt Encrypts a given plaintext using OpenPGP public key encryption with AES-256. The process involves setting up the encryption generator, adding the recipient's public key, compressing the data, creating literal data, and then writing the encrypted output in an armored format. Requires Bouncy Castle library and a valid PGPPublicKey object. ```java import java.io.*; import java.security.*; import org.bouncycastle.bcpg.*; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.openpgp.*; import org.bouncycastle.openpgp.operator.jcajce.*; Security.addProvider(new BouncyCastleProvider()); // Assume publicKey is the recipient's PGP public key PGPPublicKey publicKey = /* ... */; ByteArrayOutputStream encryptedOut = new ByteArrayOutputStream(); OutputStream armoredOut = new ArmoredOutputStream(encryptedOut); // Create encrypted data generator PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator( new JcePGPDataEncryptorBuilder(SymmetricKeyAlgorithmTags.AES_256) .setWithIntegrityPacket(true) .setSecureRandom(new SecureRandom()) .setProvider("BC")); encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(publicKey) .setProvider("BC")); // Encrypt data byte[] plaintext = "Secret document content".getBytes(); // Compress data ByteArrayOutputStream compressedOut = new ByteArrayOutputStream(); PGPCompressedDataGenerator compGen = new PGPCompressedDataGenerator( CompressionAlgorithmTags.ZIP); OutputStream compressedStream = compGen.open(compressedOut); // Create literal data PGPLiteralDataGenerator litGen = new PGPLiteralDataGenerator(); OutputStream litOut = litGen.open(compressedStream, PGPLiteralData.BINARY, "filename.txt", plaintext.length, new Date()); litOut.write(plaintext); litOut.close(); compGen.close(); // Write encrypted output byte[] compressedData = compressedOut.toByteArray(); OutputStream encOut = encGen.open(armoredOut, compressedData.length); encOut.write(compressedData); encOut.close(); armoredOut.close(); System.out.println("Encrypted PGP message:\n" + encryptedOut.toString()); ``` -------------------------------- ### Check Native Acceleration Status with Bouncy Castle Java Source: https://context7.com/bcgit/bc-lts-java/llms.txt Queries and prints the status of available native hardware acceleration features supported by the Bouncy Castle library. This can be checked programmatically or via a command-line utility. ```java import org.bouncycastle.util.DumpInfo; // Print full native status information // java -cp bcprov-lts8on-2.73.10.jar org.bouncycastle.util.DumpInfo -a // Programmatic check import org.bouncycastle.crypto.CryptoServicesRegistrar; import org.bouncycastle.crypto.NativeServices; // Check if specific native features are available boolean hasNativeAES = CryptoServicesRegistrar.hasEnabledService(NativeServices.AES_ECB); boolean hasNativeSHA256 = CryptoServicesRegistrar.hasEnabledService(NativeServices.SHA256); boolean hasNativeGCM = CryptoServicesRegistrar.hasEnabledService(NativeServices.AES_GCM); System.out.println("Native AES/ECB: " + hasNativeAES); System.out.println("Native SHA-256: " + hasNativeSHA256); System.out.println("Native AES/GCM: " + hasNativeGCM); // Get info string String info = CryptoServicesRegistrar.getInfo(); System.out.println(info); // Output: BouncyCastle APIs (LTS edition) v2.73.10 ```