### Build Examples Source: https://github.com/bcgit/bc-kotlin/blob/main/README.md Navigate to the examples directory and build the project using Gradle. This compiles the example code into .class files. ```bash cd examples gradle build cd .. ``` -------------------------------- ### Run Example (MakeV3SelfSignedCertificateKt) Source: https://github.com/bcgit/bc-kotlin/blob/main/README.md Execute the 'main' method of a specific example class. Ensure all necessary Bouncy Castle JARs and example classes are in the classpath. ```bash kotlin -cp kcrypto/build/libs/bc-kcrypto-0.0.9.jar:bc-jars-reg/bcprov-jdk18on-173.jar:bc-jars-reg/bcpkix-jdk18on-173.jar:bc-jars-reg/bcutil-jdk18on-173.jar:examples/build/classes/kotlin/main MakeV3SelfSignedCertificateKt ``` -------------------------------- ### Run Example (MakeDualCertificateAndDualCrlKt) Source: https://github.com/bcgit/bc-kotlin/blob/main/README.md Execute the 'main' method for generating hybrid certificates and CRLs. Ensure all necessary Bouncy Castle JARs and example classes are in the classpath. ```bash kotlin -cp kcrypto/build/libs/bc-kcrypto-0.0.9.jar:bc-jars-reg/bcprov-jdk18on-173.jar:bc-jars-reg/bcpkix-jdk18on-173.jar:bc-jars-reg/bcutil-jdk18on-173.jar:examples/build/classes/kotlin/main MakeDualCertificateAndDualCrlKt ``` -------------------------------- ### Example: Certificate Builder Initialization Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Certificates.md Shows an example of initializing a CertificateBuilder with a signing key, a PKCS1 signature specification using SHA256, and the issuer's name. ```kotlin val builder = CertificateBuilder(signingKey, PKCS1SigSpec(Digest.SHA256), issuerName) ``` -------------------------------- ### Complete PKCS#10 and Encrypted Key Workflow Example Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/PKCS.md A comprehensive example demonstrating the generation of a key pair, creation of a PKCS#10 certificate signing request, encryption of the private key for safekeeping, and writing both to PEM files. ```kotlin // Generate key pair val kp = KCryptoServices.signingKeyPair(RSAGenSpec(2048)) // Create subject name val subjectName = X500NameBuilder() .addRDN(BCStyle.C, "US") .addRDN(BCStyle.ST, "CA") .addRDN(BCStyle.L, "San Francisco") .addRDN(BCStyle.O, "Example Corp") .addRDN(BCStyle.CN, "www.example.com") .build() // Build PKCS#10 request val request = PKCS10RequestBuilder(kp, PKCS1SigSpec(Digest.SHA256), subjectName) .setLeaveOffEmptyAttributes(true) .build() // Create encrypted private key for safekeeping val encryptedKey = PKCS8EncryptedPrivateKeyBuilder(kp.signingKey) .build( "SecurePassword123!", GCMSpec(), PBKDF2Spec(...) ) // Write to PEM files OutputStreamWriter(FileOutputStream("request.pem")).writePEMObject(request) OutputStreamWriter(FileOutputStream("key.pem")).writePEMObject(encryptedKey) ``` -------------------------------- ### Example: Signing Data with SigningKeyPair Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Keys.md Demonstrates creating a SigningKeyPair, obtaining a signature calculator, writing data, and generating a signature. ```kotlin val kp = KCryptoServices.signingKeyPair(RSAGenSpec(2048)) val calculator = kp.signatureCalculator(PKCS1SigSpec(Digest.SHA256)) calculator.stream.write(myData) val signature = calculator.signature() ``` -------------------------------- ### Certificate DSL Example Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Certificates.md Example demonstrating the usage of the Certificate DSL for fluent certificate building. ```APIDOC ## Certificate DSL Support ### Description The library provides Kotlin DSL functions for fluent certificate building. ### Example: ```kotlin val cert = certificate { issuer = issuerSigningKey signature = PKCS1SigSpec(Digest.SHA256) subject = subjectName serialNumber = BigInteger.ONE subjectPublicKey = subjectPublicKey validity { notBefore = Date() notAfter = Date(System.currentTimeMillis() + 365L * 24 * 60 * 60 * 1000) } extensions { basicConstraints(true) keyUsage(...) } } ``` ``` -------------------------------- ### Example: Verifying a Signature with VerificationKey Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Keys.md Demonstrates creating a signature verifier, writing signed data, and verifying the signature. ```kotlin val verifier = pubKey.signatureVerifier(PKCS1SigSpec(Digest.SHA256)) verifier.stream.write(signedData) val isValid = verifier.verify(signature) verifier.close() ``` -------------------------------- ### Example: Signing Data with SigningKey Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Keys.md Demonstrates obtaining a SigningKey, creating a signature calculator, writing data, generating a signature, and closing the calculator. ```kotlin val sigKey = kp.signingKey val calculator = sigKey.signatureCalculator(PKCS1SigSpec(Digest.SHA256)) calculator.stream.write(dataToSign) val signature = calculator.signature() calculator.close() ``` -------------------------------- ### Example: Encrypting Data with EncryptionKey Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Keys.md Demonstrates creating an encryptor and encrypting plaintext into ciphertext. ```kotlin val encryptor = pubKey.singleBlockEncryptor(OAEPSpec(Digest.SHA256)) val ciphertext = encryptor.encrypt(plaintext) ``` -------------------------------- ### Run Kotlin Script Example (MakeFullPath) Source: https://github.com/bcgit/bc-kotlin/blob/main/README.md Execute a Kotlin script using 'kotlinc'. Ensure the necessary Bouncy Castle JARs are in the classpath. ```bash kotlinc -cp kcrypto/build/libs/bc-kcrypto-0.0.9.jar:bc-jars-fips/bc-fips-1.0.2.3.jar:bc-jars-fips/bcpkix-fips-1.0.6.jar -script scripts/MakeFullPath.kts ``` -------------------------------- ### Run Kotlin Script Example (Falcon) Source: https://github.com/bcgit/bc-kotlin/blob/main/README.md Execute a Kotlin script using 'kotlin'. Ensure the necessary Bouncy Castle JARs are in the classpath. ```bash kotlin -cp kcrypto/build/libs/bc-kcrypto-0.0.9.jar:bc-jars-reg/bcprov-jdk18on-173.jar:bc-jars-reg/bcpkix-jdk18on-173.jar:bc-jars-reg/bcutil-jdk18on-173.jar scripts/Falcon.kts ``` -------------------------------- ### Complete Signature Example Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Signature.md Demonstrates the end-to-end process of generating a key pair, signing data, and verifying the signature using PKCS1SigSpec and SHA256. ```kotlin import org.bouncycastle.kcrypto.* import org.bouncycastle.kcrypto.spec.asymmetric.PKCS1SigSpec // Generate a signing key pair val kp = KCryptoServices.signingKeyPair(RSAGenSpec(2048)) // Data to sign val dataToSign = "Important message".toByteArray() // Create a signature calculator val calculator = kp.signingKey.signatureCalculator(PKCS1SigSpec(Digest.SHA256)) // Write data to be signed calculator.stream.write(dataToSign) calculator.stream.close() // Get the signature val signature = calculator.signature() calculator.close() // Now verify the signature val verifier = kp.verificationKey.signatureVerifier(PKCS1SigSpec(Digest.SHA256)) // Write the same data verifier.stream.write(dataToSign) verifier.stream.close() // Verify if (verifier.verify(signature)) { println("Signature is valid!") } else { println("Signature is invalid!") } verifier.close() ``` -------------------------------- ### Example: Verifying Certificate Signature Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Certificates.md Demonstrates how to load a certificate from DER encoding and verify its signature against an issuer certificate. ```kotlin val cert = Certificate(encodedDER) val issuerCert = Certificate(issuerEncodedDER) if (cert.signatureVerifiedBy(issuerCert)) { println("Certificate signature is valid") } ``` -------------------------------- ### Build the Project Source: https://github.com/bcgit/bc-kotlin/blob/main/README.md Build the project using Gradle. Ensure you have Gradle version 6.8 or later installed. BC version 1.83 or later is required. ```bash gradle build ``` -------------------------------- ### Key Wrapping and Unwrapping Example Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Encryption.md Demonstrates wrapping a symmetric key using an encryption key and then unwrapping it using a decryption key. ```kotlin val encKey = kp.encryptionKey val wrapper = encKey.keyWrapper(OAEPSpec(Digest.SHA256)) val symKey = KCryptoServices.symmetricKey(AESGenSpec(256)) val wrappedKey = wrapper.wrap(symKey) // ... send wrappedKey over network ... val decKey = kp.decryptionKey val unwrapper = decKey.keyUnwrapper(OAEPSpec(Digest.SHA256)) val recoveredKey = unwrapper.unwrap(wrappedKey, KeyType.SYMMETRIC) ``` -------------------------------- ### Complete Encryption/Decryption Example (AES-GCM) Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Encryption.md Provides a full example of encrypting and decrypting data using AES in Galois/Counter Mode (GCM). This mode provides both confidentiality and authenticity. ```APIDOC ## AES-GCM Encryption and Decryption ### Description Demonstrates the end-to-end process of encrypting plaintext data with AES-GCM and then decrypting it back to its original form, including handling associated authenticated data (AAD). ### Method Encryption: `encryptor(GCMSpec()).outputEncryptor(outputStream) Decryption: `decryptor(GCMSpec(algId)).outputDecryptor(outputStream)` ### Endpoint N/A (SDK method calls) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body N/A (SDK method calls) ### Request Example ```kotlin // See full example in source documentation ``` ### Response #### Success Response - `recoveredPlaintext` (ByteArray) - The decrypted data, which should match the original plaintext. #### Response Example ```json { "example": "Secret message" } ``` ``` -------------------------------- ### Complete Crypto Example: Key Generation and Operations Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/types.md Demonstrates generating RSA and EC key pairs, an AES key, and performing signing with RSA-PSS and encryption with AES-GCM. Also shows key derivation using PBKDF2. ```kotlin import org.bouncycastle.kcrypto.* import org.bouncycastle.kcrypto.spec.asymmetric.* import org.bouncycastle.kcrypto.spec.symmetric.* // Generate RSA key pair for signing val rsaKeyPair = KCryptoServices.signingKeyPair(RSAGenSpec(3072)) // Generate EC key pair val ecKeyPair = KCryptoServices.signingKeyPair(ECGenSpec("secp256r1")) // Generate AES-256 key val aesKey = KCryptoServices.symmetricKey(AESGenSpec(256)) // Sign with RSA-PSS val pssSpec = PSSSigSpec(Digest.SHA256, Digest.SHA256, 32) val pssCalc = rsaKeyPair.signingKey.signatureCalculator(pssSpec) // Encrypt with AES-GCM val gcmSpec = GCMSpec() // Auto-generates IV val aeadEncryptor = aesKey.encryptor(gcmSpec) // Derive key from password with PBKDF2 val pbkdf2 = PBKDF2Spec( Digest.SHA256, "saltsalt1234567".toByteArray(), // min 8 bytes 100000 // iterations ) val kdf = KCryptoServices.pbkdf(pbkdf2, AESGenSpec(256)) ``` -------------------------------- ### RSA Single-Block Encryption Example Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Encryption.md Demonstrates how to encrypt plaintext using an RSA encryption key and OAEP padding. ```kotlin val encKey = kp.encryptionKey val encryptor = encKey.singleBlockEncryptor(OAEPSpec(Digest.SHA256)) val ciphertext = encryptor.encrypt(plaintext) ``` -------------------------------- ### Calculate Signature and Index with LMS Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Signature.md Example of calculating a signature using an LMS signing key, which is a stateful algorithm. It demonstrates how to obtain both the signature and its associated index. ```kotlin val lmsKey = kp.signingKey // LMS-based signing key val calc = lmsKey.signatureCalculator(LMSSigSpec()) calc.stream.write(data) calc.stream.close() val signature = calc.signature() val signatureIndex = calc.index() // LMS maintains an index println("Created signature at index $signatureIndex") ``` -------------------------------- ### PKCS#10 and Encrypted Key Workflow Example Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/PKCS.md Demonstrates a complete workflow involving key pair generation, PKCS#10 request building, and creating an encrypted private key. ```APIDOC ## Example: Complete PKCS#10 and Encrypted Key Workflow ### Description Demonstrates a complete workflow involving key pair generation, PKCS#10 request building, and creating an encrypted private key. ### Example ```kotlin // Generate key pair val kp = KCryptoServices.signingKeyPair(RSAGenSpec(2048)) // Create subject name val subjectName = X500NameBuilder() .addRDN(BCStyle.C, "US") .addRDN(BCStyle.ST, "CA") .addRDN(BCStyle.L, "San Francisco") .addRDN(BCStyle.O, "Example Corp") .addRDN(BCStyle.CN, "www.example.com") .build() // Build PKCS#10 request val request = PKCS10RequestBuilder(kp, PKCS1SigSpec(Digest.SHA256), subjectName) .setLeaveOffEmptyAttributes(true) .build() // Create encrypted private key for safekeeping val encryptedKey = PKCS8EncryptedPrivateKeyBuilder(kp.signingKey) .build( "SecurePassword123!", GCMSpec(), PBKDF2Spec(...) ) // Write to PEM files OutputStreamWriter(FileOutputStream("request.pem")).writePEMObject(request) OutputStreamWriter(FileOutputStream("key.pem")).writePEMObject(encryptedKey) ``` ``` -------------------------------- ### MAC Calculation and Verification Example Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Keys.md Demonstrates the complete process of generating a MAC key, calculating a MAC value for data, and then verifying that MAC value using a `MacVerifier`. Ensure the same algorithm specification is used for both calculation and verification. ```kotlin val macKey = KCryptoServices.authenticationKey(HMacSHA256GenSpec()) val calculator = macKey.macCalculator(HMacSpec(Digest.SHA256)) calculator.stream.write(data) val macValue = calculator.mac() calculator.close() val verifier = macKey.macVerifier(HMacSpec(Digest.SHA256)) verifier.stream.write(data) val isValid = verifier.verify(macValue) verifier.close() ``` -------------------------------- ### Complete Bouncy Castle Kotlin Initialization Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/configuration.md This example shows the full process of initializing cryptographic components, including key generation, encryption, and export. Ensure the Bouncy Castle provider is correctly configured before running. ```kotlin import org.bouncycastle.jce.provider.BouncyCastleProvider import org.bouncycastle.kcrypto.* import org.bouncycastle.kcrypto.spec.asymmetric.* import org.bouncycastle.kcrypto.spec.symmetric.* import org.bouncycastle.kutil.findBCProvider import java.io.OutputStreamWriter import java.io.FileOutputStream import java.util.* fun main() { // 1. Configure provider KCryptoServices.setProvider(findBCProvider()) // 2. Generate key pair val kp = KCryptoServices.signingKeyPair(RSAGenSpec(2048)) // 3. Create symmetric key val symKey = KCryptoServices.symmetricKey(AESGenSpec(256)) // 4. Generate PBKDF2 parameters val salt = ByteArray(16) { Random().nextInt(256).toByte() } val kdf = KCryptoServices.pbkdf( PBKDF2Spec(Digest.SHA256, salt, 100000), AESGenSpec(256) ) // 5. Encrypt private key val encryptedKey = PKCS8EncryptedPrivateKeyBuilder(kp.signingKey) .build( "MyPassword123!", GCMSpec(), PBKDF2Spec(Digest.SHA256, salt, 100000) ) // 6. Export to files OutputStreamWriter(FileOutputStream("private.enc")).use { w -> w.writePEMObject(encryptedKey) } println("Keys initialized and exported successfully") } ``` -------------------------------- ### Example: Encrypting a Private Key Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/PKCS.md Demonstrates how to use the PKCS8EncryptedPrivateKeyBuilder to encrypt a signing key with a password, GCM encryption, and PBKDF2 key derivation. The resulting encrypted key can be written to a PEM file. ```kotlin val encryptedKey = PKCS8EncryptedPrivateKeyBuilder(signingKey) .build( "myPassword", GCMSpec(), PBKDF2Spec(...) ) // encryptedKey.encoding can be written to a PEM file ``` -------------------------------- ### Example: Build CRL Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Certificates.md Demonstrates the process of building a Certificate Revocation List. It involves creating a CRLBuilder, setting update dates, adding a revoked entry, and finally building the CRL. ```kotlin val crlBuilder = CRLBuilder(signingKey, PKCS1SigSpec(Digest.SHA256), issuerName) .setThisUpdate(Date()) .setNextUpdate(Date(System.currentTimeMillis() + 7L * 24 * 60 * 60 * 1000)) .addCRLEntry(BigInteger.valueOf(100), Date(), RevocationReason.UNSPECIFIED) val crl = crlBuilder.build() ``` -------------------------------- ### Signing Key Pair Generation DSL Source: https://github.com/bcgit/bc-kotlin/blob/main/ADDITIONS.md Example of how to generate a signing key pair using a DSL. Replace and with specific values for the desired algorithm. ```kotlin var kp = signingKeyPair { { = ... } } ``` -------------------------------- ### Example: Build Certificate for Subject Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Certificates.md Demonstrates building a certificate for a subject. It involves generating a key pair, defining the subject's distinguished name, and then using the CertificateBuilder to set validity dates and build the certificate. ```kotlin val kp = KCryptoServices.signingKeyPair(RSAGenSpec(2048)) val subject = X500NameBuilder() .addRDN(BCStyle.C, "AU") .addRDN(BCStyle.O, "Example Corp") .addRDN(BCStyle.CN, "example.com") .build() val cert = CertificateBuilder(kp.signingKey, PKCS1SigSpec(Digest.SHA256), subject) .setNotBefore(Date()) .setNotAfter(Date(System.currentTimeMillis() + 365L * 24 * 60 * 60 * 1000)) .build(BigInteger.ONE, kp.verificationKey) ``` -------------------------------- ### Complete RSA Encryption Example Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Encryption.md Illustrates how to perform single-block encryption and decryption using RSA with OAEP padding. This is suitable for encrypting small amounts of data, like symmetric keys. ```APIDOC ## RSA Encryption and Decryption (OAEP) ### Description Shows how to encrypt a small piece of data using an RSA public key with OAEP padding and then decrypt it using the corresponding private key. ### Method Encryption: `singleBlockEncryptor(OAEPSpec()).encrypt(plaintext)` Decryption: `singleBlockDecryptor(OAEPSpec()).decrypt(ciphertext)` ### Endpoint N/A (SDK method calls) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body N/A (SDK method calls) ### Request Example ```kotlin // See full example in source documentation ``` ### Response #### Success Response - `recovered` (ByteArray) - The decrypted data, which should match the original plaintext. #### Response Example ```json { "example": "Secret" } ``` ``` -------------------------------- ### Create Signature Calculator with PKCS1SigSpec Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Signature.md Example of creating a signature calculator using a PKCS1SigSpec, which defines the hashing algorithm (e.g., SHA-256) for RSA PKCS#1 v1.5 signatures. ```kotlin val spec = PKCS1SigSpec(Digest.SHA256) val calc = signingKey.signatureCalculator(spec) ``` -------------------------------- ### Example Certificate Generation using Kotlin DSL Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Certificates.md Demonstrates the fluent construction of an X.509 certificate using the Bouncy Castle Kotlin DSL. This includes setting issuer, signature, subject, serial number, public key, validity period, and extensions. ```kotlin val cert = certificate { issuer = issuerSigningKey signature = PKCS1SigSpec(Digest.SHA256) subject = subjectName serialNumber = BigInteger.ONE subjectPublicKey = subjectPublicKey validity { notBefore = Date() notAfter = Date(System.currentTimeMillis() + 365L * 24 * 60 * 60 * 1000) } extensions { basicConstraints(true) keyUsage(...) } } ``` -------------------------------- ### Kotlin DSL for Encrypted Private Key Creation Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/PKCS.md Provides a fluent Kotlin DSL for creating encrypted private keys. This example shows how to set the private key and encryption details using a more concise syntax. ```kotlin import org.bouncycastle.kcrypto.pkcs.dsl.encryptedPrivateKey import org.bouncycastle.kcrypto.dsl.key val encryptedKey = encryptedPrivateKey { privateKey = signingKey encryption { AESGCM using key("000102030405060708090a0b0c0d0e0f") } } ``` -------------------------------- ### Generate and Sign a Certificate Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/README.md Generates an RSA key pair, builds a self-signed X.509 certificate, and saves it to a PEM file. Requires Bouncy Castle provider setup and specific algorithm specifications. ```kotlin import org.bouncycastle.kcrypto.* import org.bouncycastle.kcrypto.spec.asymmetric.* import org.bouncycastle.asn1.x500.X500NameBuilder import org.bouncycastle.asn1.x500.style.BCStyle import java.math.BigInteger import java.util.Date // Setup provider KCryptoServices.setProvider(findBCProvider()) // Generate key pair val kp = KCryptoServices.signingKeyPair(RSAGenSpec(2048)) // Create subject name val subject = X500NameBuilder() .addRDN(BCStyle.C, "US") .addRDN(BCStyle.O, "Example Corp") .addRDN(BCStyle.CN, "www.example.com") .build() // Build self-signed certificate val cert = CertificateBuilder( kp.signingKey, PKCS1SigSpec(Digest.SHA256), subject ) .setNotBefore(Date()) .setNotAfter(Date(System.currentTimeMillis() + 365L * 24 * 60 * 60 * 1000)) .build(BigInteger.ONE, kp.verificationKey) // Save certificate OutputStreamWriter(FileOutputStream("cert.pem")).writePEMObject(cert) ``` -------------------------------- ### Set Certificate Validity Start Date Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Certificates.md Sets the 'notBefore' date for the certificate, defining the earliest date from which the certificate is considered valid. Returns the builder for chaining. ```kotlin fun setNotBefore(startDate: Date): CertificateBuilder ``` -------------------------------- ### Compute Hash Value using Digest Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Signature.md Example of computing a hash value using a predefined digest algorithm like SHA-256. Ensure the digest calculator is properly closed after use. ```kotlin val digest = Digest.SHA256 val calculator = digest.digestCalculator() calculator.stream.write(data) calculator.stream.close() val hash = calculator.digest() ``` -------------------------------- ### Symmetric Encryption Example Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Encryption.md Encrypts plaintext using a symmetric key and AES-GCMSpec, writing the ciphertext to a ByteArrayOutputStream. Ensure the key and algorithm specification are correctly initialized. ```kotlin val key = KCryptoServices.symmetricKey(AESGenSpec(256)) val encryptor = key.encryptor(GCMSpec()) val outputEnc = encryptor.outputEncryptor(ByteArrayOutputStream()) outputEnc.encStream.write(plaintext) outputEnc.encStream.close() val ciphertext = outputEnc.encStream.toByteArray() ``` -------------------------------- ### Calculate Digital Signature Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Signature.md Example of calculating a digital signature for a message using a signing key and a specific signature specification (e.g., PKCS1SigSpec with SHA-256). The stream must be closed after writing data, and the calculator should be closed afterward. ```kotlin val signingKey = kp.signingKey val calc = signingKey.signatureCalculator(PKCS1SigSpec(Digest.SHA256)) calc.stream.write(messageToSign) calc.stream.close() val signature = calc.signature() calc.close() ``` -------------------------------- ### Verify Digital Signature Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Signature.md Example of verifying a digital signature against signed data using a verification key and a signature specification. The stream must be closed after writing data, and the verifier should be closed afterward. ```kotlin val verificationKey = kp.verificationKey val verifier = verificationKey.signatureVerifier(PKCS1SigSpec(Digest.SHA256)) verifier.stream.write(signedData) verifier.stream.close() if (verifier.verify(signature)) { println("Signature is valid") } else { println("Signature is invalid") } verifier.close() ``` -------------------------------- ### CertificateBuilder.setNotBefore Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Certificates.md Sets the validity start date for the certificate being built. Returns the builder for chaining. ```APIDOC ## CertificateBuilder.setNotBefore Set the certificate validity start date. ### Method ```kotlin fun setNotBefore(startDate: Date): CertificateBuilder ``` ### Parameters #### Path Parameters - **startDate** (Date) - Required - Date from which certificate is valid ### Returns `CertificateBuilder` – for method chaining ``` -------------------------------- ### Get Signature Bytes Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Signature.md Retrieve the calculated signature bytes from a signature calculator. This method is part of the SignatureCalculator interface. ```kotlin fun signature(): ByteArray ``` -------------------------------- ### Get Computed MAC Value Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Encryption.md Retrieves the computed Message Authentication Code (MAC) value after data has been written to the stream. ```kotlin fun mac(): ByteArray ``` -------------------------------- ### Encrypt and Store a Private Key Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/README.md Demonstrates encrypting a private key using a password and a salt, then storing it in PKCS#8 format. It also shows how to decrypt it later. ```kotlin val encryptedKey = PKCS8EncryptedPrivateKeyBuilder(kp.signingKey) .build( "MyPassword123!", GCMSpec(), PBKDF2Spec( Digest.SHA256, "randomsalt1234567".toByteArray(), 100000 ) ) OutputStreamWriter(FileOutputStream("private.enc")).writePEMObject(encryptedKey) // Later: decrypt val decrypted = encryptedKey.decrypt("MyPassword123!") ``` -------------------------------- ### Close Calculator Streams in Kotlin Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/configuration.md Always close calculators, verifiers, and decryptors to release resources. This example shows manual closing. ```kotlin val calculator = signingKey.signatureCalculator(PKCS1SigSpec(Digest.SHA256)) try { calculator.stream.write(data) calculator.stream.close() val signature = calculator.signature() } finally { calculator.close() } ``` -------------------------------- ### Create and Verify a Digital Signature Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/README.md Shows how to create a digital signature for data using a private key and then verify it using the corresponding public key. Supports algorithms like PKCS#1 with SHA-256. ```kotlin val data = "Important document".toByteArray() // Sign val calculator = kp.signingKey.signatureCalculator(PKCS1SigSpec(Digest.SHA256)) calculator.stream.write(data) calculator.stream.close() val signature = calculator.signature() calculator.close() // Verify val verifier = kp.verificationKey.signatureVerifier(PKCS1SigSpec(Digest.SHA256)) verifier.stream.write(data) verifier.stream.close() val isValid = verifier.verify(signature) verifier.close() ``` -------------------------------- ### Get Signature Index for Stateful Algorithms Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Signature.md Retrieve the index of the current signature, specifically for stateful algorithms like LMS. This is useful for tracking signature versions or states. ```kotlin fun index(): Long ``` -------------------------------- ### Initialize Certificate Builder with Signing Key Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Certificates.md Constructs a CertificateBuilder using a SigningKey, a signature algorithm specification, and the issuer's X500Name. This is a common way to build certificates when you have the private signing key. ```kotlin constructor(signingKey: SigningKey, sigAlgSpec: SigAlgSpec, issuerName: X500Name) ``` -------------------------------- ### Run Kotlin Interactively Source: https://github.com/bcgit/bc-kotlin/blob/main/README.md Run Kotlin interactively and load a script. Ensure the necessary Bouncy Castle JARs are in the classpath. ```bash kotlin -cp kcrypto/build/libs/bc-kcrypto-0.0.9.jar:bc-jars-reg/bcprov-jdk18on-173.jar:bc-jars-reg/bcpkix-jdk18on-173.jar:bc-jars-reg/bcutil-jdk18on-173.jar >>> :load scripts/Falcon.kts ``` -------------------------------- ### Key Generation Performance Comparison Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/configuration.md Compares the performance of key generation for different cryptographic algorithms, highlighting that Post-Quantum Cryptography (PQC) key generation can be slow. ```kotlin // Fast (< 1 second) val rsaKp = KCryptoServices.signingKeyPair(RSAGenSpec(2048)) // Medium (1-10 seconds) val mldsaKp = KCryptoServices.signingKeyPair(MLDSAGenSpec("ML-DSA-65")) // Slow (10+ seconds) val slhdsaKp = KCryptoServices.signingKeyPair(SLHDSAGenSpec("SLH-DSA-SHA2-256f")) ``` -------------------------------- ### Complete AES-GCM Encryption and Decryption Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Encryption.md Provides a full example of encrypting and decrypting data using AES in GCM mode with associated authenticated data (AAD). This method ensures both confidentiality and integrity. ```kotlin import org.bouncycastle.kcrypto.* import org.bouncycastle.kcrypto.spec.symmetric.GCMSpec import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream // Generate AES key val key = KCryptoServices.symmetricKey(AESGenSpec(256)) // Data to encrypt val plaintext = "Secret message".toByteArray() val aad = "Header data".toByteArray() // Encrypt with AES-GCM val encryptor = key.encryptor(GCMSpec()) val ciphertextOutput = ByteArrayOutputStream() val outputEnc = encryptor.outputEncryptor(ciphertextOutput) outputEnc.aadStream.write(aad) outputEnc.aadStream.close() outputEnc.encStream.write(plaintext) outputEnc.encStream.close() outputEnc.close() val ciphertext = ciphertextOutput.toByteArray() val algId = outputEnc.algorithmIdentifier // Contains IV // Decrypt val decryptor = key.decryptor(GCMSpec(algId)) val plaintextOutput = ByteArrayOutputStream() val outputDec = decryptor.outputDecryptor(plaintextOutput) outputDec.aadStream.write(aad) outputDec.aadStream.close() outputDec.decStream.write(ciphertext) outputDec.decStream.close() outputDec.close() val recoveredPlaintext = plaintextOutput.toByteArray() assert(recoveredPlaintext.contentEquals(plaintext)) ``` -------------------------------- ### Algorithm-Specific Key Types Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/types.md Demonstrates creating algorithm-specific KeyTypes by appending an algorithm name (e.g., RSA, EC, AES) to predefined types. ```kotlin val rsaSigningKeyType = KeyType.SIGNING.forAlgorithm("RSA") val ecSigningKeyType = KeyType.SIGNING.forAlgorithm("EC") val aesKeyType = KeyType.SYMMETRIC.forAlgorithm("AES") ``` -------------------------------- ### PKCS10RequestBuilder Initialization Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/PKCS.md Initialize a PKCS10RequestBuilder using a signing key, algorithm specification, subject name, and public key. ```kotlin val builder = PKCS10RequestBuilder(kp.signingKey, PKCS1SigSpec(Digest.SHA256), subjectName, kp.verificationKey) ``` -------------------------------- ### Initialize Certificate Builder with Signature Calculator Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Certificates.md Constructs a CertificateBuilder using a direct SignatureCalculator and the issuer's X500Name. This is suitable when you have a pre-configured signature calculator. ```kotlin constructor(signatureCalculator: SignatureCalculator, issuerName: X500Name) ``` -------------------------------- ### AEAD Encryption Example Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Encryption.md Performs AEAD encryption using a symmetric key and AES-GCMSpec. It requires writing Additional Authenticated Data (AAD) before the plaintext. Ensure streams are closed properly after writing AAD and plaintext. ```kotlin val key = KCryptoServices.symmetricKey(AESGenSpec(256)) val encryptor = key.encryptor(GCMSpec()) val outputEnc = encryptor.outputEncryptor(ciphertextOutput) // Write AAD first outputEnc.aadStream.write(associatedData) outputEnc.aadStream.close() // Then write plaintext outputEnc.encStream.write(plaintext) outputEnc.encStream.close() outputEnc.close() ``` -------------------------------- ### Create Signature Calculator from SigningKeyPair Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Keys.md Obtain a signature calculator from a SigningKeyPair using a specified signature algorithm. ```kotlin fun signatureCalculator(sigAlgSpec: SigAlgSpec): SignatureCalculator ``` -------------------------------- ### Create Asymmetric Key Unwrapper Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Keys.md Creates a key unwrapper for asymmetric key unwrapping. Requires an Algorithm Specification for key unwrapping. ```kotlin fun keyUnwrapper(algSpec: AlgSpec): KeyUnwrapper ``` -------------------------------- ### build Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Certificates.md Build the Extensions object from the configured ExtensionsBuilder. ```APIDOC ## build ### Description Build the Extensions object from the configured ExtensionsBuilder. ### Method ```kotlin fun build(): Extensions ``` ### Returns - **Extensions** - The constructed Extensions object. ``` -------------------------------- ### Compute and Verify MAC Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/README.md Illustrates how to compute a Message Authentication Code (MAC) for data using a symmetric key and HMAC-SHA256, and then verify its integrity. ```kotlin val macKey = KCryptoServices.authenticationKey(HMacSHA256GenSpec()) val data = "Authenticate this".toByteArray() // Compute val calculator = macKey.macCalculator(HMacSpec(Digest.SHA256)) calculator.stream.write(data) calculator.stream.close() val macValue = calculator.mac() calculator.close() // Verify val verifier = macKey.macVerifier(HMacSpec(Digest.SHA256)) verifier.stream.write(data) verifier.stream.close() val isValid = verifier.verify(macValue) verifier.close() ``` -------------------------------- ### Create Key Wrapper from EncryptionKey Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Keys.md Obtain a key wrapper for asymmetric key wrapping using a specified algorithm specification. ```kotlin fun keyWrapper(algSpec: AlgSpec): KeyWrapper ``` -------------------------------- ### Build and Sign PKCS#10 Request Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/PKCS.md Construct and sign a PKCS#10 certification request. The 'leaveOffEmptyAttributes' option can be set to true to omit empty attributes, which some CAs may require. ```kotlin val kp = KCryptoServices.signingKeyPair(RSAGenSpec(2048)) val subjectName = X500NameBuilder() .addRDN(BCStyle.C, "AU") .addRDN(BCStyle.O, "Example Corp") .addRDN(BCStyle.CN, "example.com") .build() val request = PKCS10RequestBuilder(kp, PKCS1SigSpec(Digest.SHA256), subjectName) .setLeaveOffEmptyAttributes(true) .build() // request.encoding contains the DER-encoded request ``` -------------------------------- ### MAC Calculator and Verifier Lifecycle Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Encryption.md Demonstrates the lifecycle of MAC calculators and verifiers, including creation, data streaming, and closing resources. This ensures proper handling of cryptographic operations. ```APIDOC ## close() ### Description Close the verifier or calculator, releasing any associated resources. ### Method `close` ### Parameters None ### Request Example ```kotlin // Example usage within a larger context (see full example below) // calculator.close() // verifier.close() ``` ### Response #### Success Response No specific return value, operation completes successfully. #### Response Example None ``` -------------------------------- ### Create a PKCS#10 Certification Request Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/README.md Creates a PKCS#10 certification request using a previously generated key pair and signature specification. The request is then saved to a PEM file. ```kotlin val request = PKCS10RequestBuilder( kp, PKCS1SigSpec(Digest.SHA256), subject ) .setLeaveOffEmptyAttributes(true) .build() OutputStreamWriter(FileOutputStream("csr.pem")).writePEMObject(request) ``` -------------------------------- ### Initialize Certificate Builder from Issuer Certificate Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Certificates.md Constructs a CertificateBuilder using a SigningKey, a signature algorithm specification, and an existing issuer Certificate. The issuer's name is derived from the provided issuer certificate. ```kotlin constructor(signingKey: SigningKey, sigAlgSpec: SigAlgSpec, issuerCert: Certificate) ``` -------------------------------- ### Create Symmetric Key Unwrapper Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Keys.md Creates a symmetric key unwrapper. Requires an Algorithm Specification. ```kotlin fun keyUnwrapper(algSpec: AlgSpec): KeyUnwrapper ``` ```kotlin val key = KCryptoServices.symmetricKey(AESGenSpec(256)) val encryptor = key.encryptor(GCMSpec()) val outputEnc = encryptor.outputEncryptor(outputStream) outputEnc.use { it.encStream.write(data) } val decryptor = key.decryptor(GCMSpec(...)) val outputDec = decryptor.outputDecryptor(outputStream) outputDec.use { it.decStream.write(ciphertext) } ``` -------------------------------- ### Create MAC Calculator Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Keys.md Creates a MAC (Message Authentication Code) calculator. Requires a MAC Algorithm Specification. ```kotlin fun macCalculator(algSpec: MacAlgSpec): MacCalculator ``` -------------------------------- ### Symmetric Encryption Performance: KDF Comparison Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/configuration.md Compares the performance of PBKDF2 and Scrypt Key Derivation Functions (KDFs), noting PBKDF2 is faster than Scrypt with typical parameters. ```kotlin // Fast: PBKDF2 with 100,000 iterations (~100ms) val pbkdf2 = PBKDF2Spec(Digest.SHA256, salt, 100000) // Slow: Scrypt with typical parameters (~1s) val scrypt = ScryptSpec(salt, 16384, 8, 1) ``` -------------------------------- ### Create Signature Verifier from SigningKeyPair Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Keys.md Obtain a signature verifier from a SigningKeyPair using a specified signature algorithm. ```kotlin fun signatureVerifier(sigAlgSpec: SigAlgSpec): SignatureVerifier ``` -------------------------------- ### Change Digest Algorithm in Signature Operations Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/configuration.md Demonstrates how to create signature specifications using different digest algorithms like SHA-256, SHA-384, and SHA-512. ```kotlin val sha256Spec = PKCS1SigSpec(Digest.SHA256) val sha384Spec = PKCS1SigSpec(Digest.SHA384) val sha512Spec = PKCS1SigSpec(Digest.SHA512) ``` -------------------------------- ### SymmetricKey.keyWrapper Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Keys.md Creates a symmetric key wrapper. ```APIDOC ## SymmetricKey.keyWrapper ### Description Creates a symmetric key wrapper. ### Method Not specified (Kotlin function) ### Endpoint Not specified (Kotlin function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response Returns a `KeyWrapper`. #### Response Example None ``` -------------------------------- ### AuthenticationKey.macCalculator Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Keys.md Creates a MAC calculator for an authentication key. ```APIDOC ## AuthenticationKey.macCalculator ### Description Creates a MAC calculator. ### Method Not specified (Kotlin function) ### Endpoint Not specified (Kotlin function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response Returns a `MacCalculator`. #### Response Example None ``` -------------------------------- ### Create Authentication Key from Raw Bytes Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/KCryptoServices.md Creates an authentication key for MAC calculations directly from raw byte data and a specified key type. This is useful when you have pre-existing key material. ```kotlin fun authenticationKey(rawKey: ByteArray, keyType: KeyType): AuthenticationKey ``` -------------------------------- ### PKCS8EncryptedPrivateKeyBuilder Constructor Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/PKCS.md Initializes a builder for creating PKCS8EncryptedPrivateKey. It requires a SigningKey for encryption. ```APIDOC ## PKCS8EncryptedPrivateKeyBuilder Constructor ### Description Initializes a builder for creating PKCS8EncryptedPrivateKey. It requires a SigningKey for encryption. ### Parameters #### Path Parameters - **privateKey** (SigningKey) - Required - Private key to encrypt ``` -------------------------------- ### Wrap Signing Key Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Encryption.md Wraps a private signing key into a byte array. ```kotlin fun wrap(key: SigningKey): ByteArray ``` -------------------------------- ### Use Try-with-Resources for AutoCloseable Streams Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/configuration.md Utilize the `use` extension function for streams that support AutoCloseable, ensuring automatic resource management. ```kotlin // For streams that support AutoCloseable val outputEncryptor = key.encryptor(GCMSpec()).outputEncryptor(outputStream) outputEncryptor.use { it.encStream.write(data) } ``` -------------------------------- ### SigningKeyBuilder Extension for New Algorithm Source: https://github.com/bcgit/bc-kotlin/blob/main/ADDITIONS.md Adds a new algorithm to the SigningKeyBuilder DSL. This involves creating a new extension function that takes algorithm-specific parameters and sets the appropriate generation specification. ```kotlin fun SigningKeyBuilder.(block: Params.() -> Unit) { val p = Params().apply(block) setSpec(GenSpec(p., KCryptoServices.secureRandom)) } ``` -------------------------------- ### Set Certificate Extensions Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Certificates.md Adds X.509 v3 extensions to the certificate being built. Pass null to create a v1 certificate without extensions. Returns the builder for chaining. ```kotlin fun setExtensions(extensions: Extensions?): CertificateBuilder ``` -------------------------------- ### Calculate and Verify MAC Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Encryption.md Demonstrates the process of calculating a MAC for data using HMAC-SHA256 and then verifying its integrity. Ensure you use the same key and specification for both calculation and verification. ```kotlin val macKey = KCryptoServices.authenticationKey(HMacSHA256GenSpec()) // Calculate MAC val calculator = macKey.macCalculator(HMacSpec(Digest.SHA256)) calculator.stream.write(data) calculator.stream.close() val macValue = calculator.mac() calculator.close() // Verify MAC val verifier = macKey.macVerifier(HMacSpec(Digest.SHA256)) verifier.stream.write(data) verifier.stream.close() val isValid = verifier.verify(macValue) verifier.close() ``` -------------------------------- ### Use Explicit IV for GCM Encryption Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/configuration.md Demonstrates how to provide an explicit Initialization Vector (IV) when creating a GCMSpec for GCM encryption. ```kotlin val iv = ByteArray(12) { Random().nextInt(256).toByte() } val spec = GCMSpec(iv, 128) // Use explicit IV ``` -------------------------------- ### Create Signing Key from DER Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/KCryptoServices.md Creates a private key for signature creation from DER-encoded PrivateKeyInfo bytes. Specify the algorithm using KeyType.SIGNING.forAlgorithm. ```kotlin val privKey = KCryptoServices.signingKey(encodedPKCS8, KeyType.SIGNING.forAlgorithm("RSA")) ``` -------------------------------- ### PKCS1SigSpec Constructor Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Signature.md Constructs a PKCS#1 v1.5 signature specification, requiring a hash algorithm (Digest) to be specified. ```kotlin class PKCS1SigSpec(val digest: Digest) ``` -------------------------------- ### Signing Large Messages with Streams Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Signature.md Shows how to use streaming interfaces for signing large messages by wrapping a Signature object as an OutputStream. ```kotlin val calculator = signingKey.signatureCalculator(PKCS1SigSpec(Digest.SHA256)) // Streaming large file val fileInputStream = FileInputStream("large-file.bin") fileInputStream.copyTo(calculator.stream) calculator.stream.close() val signature = calculator.signature() ``` -------------------------------- ### CRLBuilder.build Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Certificates.md Constructs and returns the final Certificate Revocation List object. ```APIDOC ## build ### Description Build the CRL. ### Method ```kotlin fun build(): CRL ``` ### Returns `CRL` ### Request Example ```kotlin val crlBuilder = CRLBuilder(signingKey, PKCS1SigSpec(Digest.SHA256), issuerName) .setThisUpdate(Date()) .setNextUpdate(Date(System.currentTimeMillis() + 7L * 24 * 60 * 60 * 1000)) .addCRLEntry(BigInteger.valueOf(100), Date(), RevocationReason.UNSPECIFIED) val crl = crlBuilder.build() ``` ``` -------------------------------- ### PQC Maven Dependency Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/configuration.md Include the BCPQC provider dependency in your Maven project to enable automatic support for post-quantum algorithms like Falcon, ML-DSA, and ML-KEM. ```xml org.bouncycastle bcprov-jdk18on 1.83+ ``` -------------------------------- ### Create Password-Based Key Derivation Function (PBKDF) Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/KCryptoServices.md Initializes a PBKDF operator for deriving cryptographic keys from passwords. Supports configurations like ScryptSpec or PBKDF2Spec and various target key specifications. ```kotlin fun pbkdf(kdfConfig: PBKDFAlgSpec, keySpec: KeyGenSpec): PBKDF ``` ```kotlin val pbkdf = KCryptoServices.pbkdf(PBKDF2Spec(...), AESGenSpec(256)) ``` -------------------------------- ### Complete RSA Encryption and Decryption Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Encryption.md Demonstrates encrypting and decrypting data using RSA with OAEP padding. This is suitable for encrypting small amounts of data, typically symmetric keys. ```kotlin // Generate RSA key pair val kp = KCryptoServices.encryptingKeyPair(RSAGenSpec(2048)) // Encrypt val encryptor = kp.encryptionKey.singleBlockEncryptor(OAEPSpec(Digest.SHA256)) val plaintext = "Secret".toByteArray() val ciphertext = encryptor.encrypt(plaintext) // Decrypt val decryptor = kp.decryptionKey.singleBlockDecryptor(OAEPSpec(Digest.SHA256)) val recovered = decryptor.decrypt(ciphertext) assert(recovered.contentEquals(plaintext)) ``` -------------------------------- ### KeyWrapper wrap (SigningKey) Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Encryption.md Wraps (encrypts) a private signing key into a byte array. ```APIDOC ## wrap SigningKey KeyWrapper ### Description Wrap a private signing key using the KeyWrapper. ### Method wrap ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **key** (SigningKey) - Required - Private key to wrap ### Response #### Success Response (200) - **ByteArray** – Wrapped key bytes #### Response Example None provided in source. ``` -------------------------------- ### Create a Digest Calculator Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/Signature.md Obtain a calculator for computing hash values of data. This is used for standard hashing operations. ```kotlin fun digestCalculator(): DigestCalculator ``` -------------------------------- ### Mayo Post-Quantum Signature Key Generation Source: https://github.com/bcgit/bc-kotlin/blob/main/_autodocs/types.md Use MayoGenSpec for post-quantum Mayo signature key generation. Specify the parameter set, such as "MAYO-1", "MAYO-2", "MAYO-3", or "MAYO-5", and optionally the random source. ```kotlin class MayoGenSpec(val parameterSet: String, override val random: SecureRandom = KCryptoServices.secureRandom) : SignGenSpec ```